Skip to content

Commit a0e0466

Browse files
jbrockmendelproost
authored andcommitted
ANN: types for _create_storer (pandas-dev#29757)
1 parent a4ef8cc commit a0e0466

File tree

1 file changed

+37
-27
lines changed

1 file changed

+37
-27
lines changed

pandas/io/pytables.py

+37-27
Original file line numberDiff line numberDiff line change
@@ -174,9 +174,6 @@ class DuplicateWarning(Warning):
174174
and is the default for append operations
175175
"""
176176

177-
# map object types
178-
_TYPE_MAP = {Series: "series", DataFrame: "frame"}
179-
180177
# storer class map
181178
_STORER_MAP = {
182179
"series": "SeriesFixed",
@@ -797,9 +794,10 @@ def select_as_coordinates(
797794
stop : integer (defaults to None), row number to stop selection
798795
"""
799796
where = _ensure_term(where, scope_level=1)
800-
return self.get_storer(key).read_coordinates(
801-
where=where, start=start, stop=stop, **kwargs
802-
)
797+
tbl = self.get_storer(key)
798+
if not isinstance(tbl, Table):
799+
raise TypeError("can only read_coordinates with a table")
800+
return tbl.read_coordinates(where=where, start=start, stop=stop, **kwargs)
803801

804802
def select_column(self, key: str, column: str, **kwargs):
805803
"""
@@ -820,7 +818,10 @@ def select_column(self, key: str, column: str, **kwargs):
820818
is part of a data block)
821819
822820
"""
823-
return self.get_storer(key).read_column(column=column, **kwargs)
821+
tbl = self.get_storer(key)
822+
if not isinstance(tbl, Table):
823+
raise TypeError("can only read_column with a table")
824+
return tbl.read_column(column=column, **kwargs)
824825

825826
def select_as_multiple(
826827
self,
@@ -903,8 +904,12 @@ def select_as_multiple(
903904
elif t.nrows != nrows:
904905
raise ValueError("all tables must have exactly the same nrows!")
905906

907+
# The isinstance checks here are redundant with the check above,
908+
# but necessary for mypy; see GH#29757
909+
_tbls = [x for x in tbls if isinstance(x, Table)]
910+
906911
# axis is the concentration axes
907-
axis = list({t.non_index_axes[0][0] for t in tbls})[0]
912+
axis = list({t.non_index_axes[0][0] for t in _tbls})[0]
908913

909914
def func(_start, _stop, _where):
910915

@@ -1005,9 +1010,9 @@ def remove(self, key: str, where=None, start=None, stop=None):
10051010
)
10061011

10071012
# we are actually trying to remove a node (with children)
1008-
s = self.get_node(key)
1009-
if s is not None:
1010-
s._f_remove(recursive=True)
1013+
node = self.get_node(key)
1014+
if node is not None:
1015+
node._f_remove(recursive=True)
10111016
return None
10121017

10131018
# remove the node
@@ -1189,7 +1194,7 @@ def create_table_index(self, key: str, **kwargs):
11891194
if s is None:
11901195
return
11911196

1192-
if not s.is_table:
1197+
if not isinstance(s, Table):
11931198
raise TypeError("cannot create table index on a Fixed format store")
11941199
s.create_index(**kwargs)
11951200

@@ -1278,7 +1283,7 @@ def get_node(self, key: str):
12781283
except _table_mod.exceptions.NoSuchNodeError: # type: ignore
12791284
return None
12801285

1281-
def get_storer(self, key: str):
1286+
def get_storer(self, key: str) -> Union["GenericFixed", "Table"]:
12821287
""" return the storer object for a key, raise if not in the file """
12831288
group = self.get_node(key)
12841289
if group is None:
@@ -1331,7 +1336,7 @@ def copy(
13311336
new_store.remove(k)
13321337

13331338
data = self.select(k)
1334-
if s.is_table:
1339+
if isinstance(s, Table):
13351340

13361341
index: Union[bool, list] = False
13371342
if propindexes:
@@ -1403,13 +1408,16 @@ def _validate_format(self, format: str, kwargs: Dict[str, Any]) -> Dict[str, Any
14031408

14041409
return kwargs
14051410

1406-
def _create_storer(self, group, format=None, value=None, append=False, **kwargs):
1411+
def _create_storer(
1412+
self, group, format=None, value=None, **kwargs
1413+
) -> Union["GenericFixed", "Table"]:
14071414
""" return a suitable class to operate """
14081415

14091416
def error(t):
1410-
raise TypeError(
1417+
# return instead of raising so mypy can tell where we are raising
1418+
return TypeError(
14111419
f"cannot properly create the storer for: [{t}] [group->"
1412-
f"{group},value->{type(value)},format->{format},append->{append},"
1420+
f"{group},value->{type(value)},format->{format},"
14131421
f"kwargs->{kwargs}]"
14141422
)
14151423

@@ -1421,6 +1429,7 @@ def error(t):
14211429
if value is None:
14221430

14231431
_tables()
1432+
assert _table_mod is not None # for mypy
14241433
if getattr(group, "table", None) or isinstance(
14251434
group, _table_mod.table.Table
14261435
):
@@ -1432,11 +1441,11 @@ def error(t):
14321441
"nor a value are passed"
14331442
)
14341443
else:
1435-
1444+
_TYPE_MAP = {Series: "series", DataFrame: "frame"}
14361445
try:
14371446
pt = _TYPE_MAP[type(value)]
14381447
except KeyError:
1439-
error("_TYPE_MAP")
1448+
raise error("_TYPE_MAP")
14401449

14411450
# we are actually a table
14421451
if format == "table":
@@ -1447,7 +1456,7 @@ def error(t):
14471456
try:
14481457
return globals()[_STORER_MAP[pt]](self, group, **kwargs)
14491458
except KeyError:
1450-
error("_STORER_MAP")
1459+
raise error("_STORER_MAP")
14511460

14521461
# existing node (and must be a table)
14531462
if tt is None:
@@ -1488,7 +1497,7 @@ def error(t):
14881497
try:
14891498
return globals()[_TABLE_MAP[tt]](self, group, **kwargs)
14901499
except KeyError:
1491-
error("_TABLE_MAP")
1500+
raise error("_TABLE_MAP")
14921501

14931502
def _write_to_group(
14941503
self,
@@ -1534,9 +1543,7 @@ def _write_to_group(
15341543
group = self._handle.create_group(path, p)
15351544
path = new_path
15361545

1537-
s = self._create_storer(
1538-
group, format, value, append=append, encoding=encoding, **kwargs
1539-
)
1546+
s = self._create_storer(group, format, value, encoding=encoding, **kwargs)
15401547
if append:
15411548
# raise if we are trying to append to a Fixed format,
15421549
# or a table that exists (and we are putting)
@@ -1553,7 +1560,7 @@ def _write_to_group(
15531560
# write the object
15541561
s.write(obj=value, append=append, complib=complib, **kwargs)
15551562

1556-
if s.is_table and index:
1563+
if isinstance(s, Table) and index:
15571564
s.create_index(columns=index)
15581565

15591566
def _read_group(self, group, **kwargs):
@@ -1584,11 +1591,12 @@ class TableIterator:
15841591

15851592
chunksize: Optional[int]
15861593
store: HDFStore
1594+
s: Union["GenericFixed", "Table"]
15871595

15881596
def __init__(
15891597
self,
15901598
store: HDFStore,
1591-
s,
1599+
s: Union["GenericFixed", "Table"],
15921600
func,
15931601
where,
15941602
nrows,
@@ -1651,7 +1659,7 @@ def get_result(self, coordinates: bool = False):
16511659

16521660
# return the actual iterator
16531661
if self.chunksize is not None:
1654-
if not self.s.is_table:
1662+
if not isinstance(self.s, Table):
16551663
raise TypeError("can only use an iterator or chunksize on a table")
16561664

16571665
self.coordinates = self.s.read_coordinates(where=self.where)
@@ -1660,6 +1668,8 @@ def get_result(self, coordinates: bool = False):
16601668

16611669
# if specified read via coordinates (necessary for multiple selections
16621670
if coordinates:
1671+
if not isinstance(self.s, Table):
1672+
raise TypeError("can only read_coordinates on a table")
16631673
where = self.s.read_coordinates(
16641674
where=self.where, start=self.start, stop=self.stop
16651675
)

0 commit comments

Comments
 (0)