Skip to content

Commit 698522f

Browse files
jbrockmendeljreback
authored andcommitted
TYP: add string annotations in io.pytables (#29682)
1 parent cd56708 commit 698522f

File tree

1 file changed

+46
-30
lines changed

1 file changed

+46
-30
lines changed

pandas/io/pytables.py

+46-30
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import os
1010
import re
1111
import time
12-
from typing import List, Optional, Type, Union
12+
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Type, Union
1313
import warnings
1414

1515
import numpy as np
@@ -55,6 +55,10 @@
5555
from pandas.io.common import _stringify_path
5656
from pandas.io.formats.printing import adjoin, pprint_thing
5757

58+
if TYPE_CHECKING:
59+
from tables import File # noqa:F401
60+
61+
5862
# versioning attribute
5963
_version = "0.15.2"
6064

@@ -465,6 +469,8 @@ class HDFStore:
465469
>>> store.close()
466470
"""
467471

472+
_handle: Optional["File"]
473+
468474
def __init__(
469475
self,
470476
path,
@@ -535,7 +541,7 @@ def __getattr__(self, name):
535541
)
536542
)
537543

538-
def __contains__(self, key):
544+
def __contains__(self, key: str):
539545
""" check for existence of this key
540546
can match the exact pathname or the pathnm w/o the leading '/'
541547
"""
@@ -560,7 +566,7 @@ def __enter__(self):
560566
def __exit__(self, exc_type, exc_value, traceback):
561567
self.close()
562568

563-
def keys(self):
569+
def keys(self) -> List[str]:
564570
"""
565571
Return a list of keys corresponding to objects stored in HDFStore.
566572
@@ -698,13 +704,13 @@ def flush(self, fsync: bool = False):
698704
except OSError:
699705
pass
700706

701-
def get(self, key):
707+
def get(self, key: str):
702708
"""
703709
Retrieve pandas object stored in file.
704710
705711
Parameters
706712
----------
707-
key : object
713+
key : str
708714
709715
Returns
710716
-------
@@ -718,7 +724,7 @@ def get(self, key):
718724

719725
def select(
720726
self,
721-
key,
727+
key: str,
722728
where=None,
723729
start=None,
724730
stop=None,
@@ -733,7 +739,7 @@ def select(
733739
734740
Parameters
735741
----------
736-
key : object
742+
key : str
737743
Object being retrieved from file.
738744
where : list, default None
739745
List of Term (or convertible) objects, optional.
@@ -784,13 +790,15 @@ def func(_start, _stop, _where):
784790

785791
return it.get_result()
786792

787-
def select_as_coordinates(self, key, where=None, start=None, stop=None, **kwargs):
793+
def select_as_coordinates(
794+
self, key: str, where=None, start=None, stop=None, **kwargs
795+
):
788796
"""
789797
return the selection as an Index
790798
791799
Parameters
792800
----------
793-
key : object
801+
key : str
794802
where : list of Term (or convertible) objects, optional
795803
start : integer (defaults to None), row number to start selection
796804
stop : integer (defaults to None), row number to stop selection
@@ -800,15 +808,16 @@ def select_as_coordinates(self, key, where=None, start=None, stop=None, **kwargs
800808
where=where, start=start, stop=stop, **kwargs
801809
)
802810

803-
def select_column(self, key, column, **kwargs):
811+
def select_column(self, key: str, column: str, **kwargs):
804812
"""
805813
return a single column from the table. This is generally only useful to
806814
select an indexable
807815
808816
Parameters
809817
----------
810-
key : object
811-
column: the column of interest
818+
key : str
819+
column: str
820+
The column of interest.
812821
813822
Raises
814823
------
@@ -966,7 +975,7 @@ def put(self, key, value, format=None, append=False, **kwargs):
966975
kwargs = self._validate_format(format, kwargs)
967976
self._write_to_group(key, value, append=append, **kwargs)
968977

969-
def remove(self, key, where=None, start=None, stop=None):
978+
def remove(self, key: str, where=None, start=None, stop=None):
970979
"""
971980
Remove pandas object partially by specifying the where condition
972981
@@ -1152,16 +1161,17 @@ def append_to_multiple(
11521161

11531162
self.append(k, val, data_columns=dc, **kwargs)
11541163

1155-
def create_table_index(self, key, **kwargs):
1156-
""" Create a pytables index on the table
1164+
def create_table_index(self, key: str, **kwargs):
1165+
"""
1166+
Create a pytables index on the table.
1167+
11571168
Parameters
11581169
----------
1159-
key : object (the node to index)
1170+
key : str
11601171
11611172
Raises
11621173
------
1163-
raises if the node is not a table
1164-
1174+
TypeError: raises if the node is not a table
11651175
"""
11661176

11671177
# version requirements
@@ -1247,17 +1257,19 @@ def walk(self, where="/"):
12471257

12481258
yield (g._v_pathname.rstrip("/"), groups, leaves)
12491259

1250-
def get_node(self, key):
1260+
def get_node(self, key: str):
12511261
""" return the node with the key or None if it does not exist """
12521262
self._check_if_open()
1263+
if not key.startswith("/"):
1264+
key = "/" + key
1265+
1266+
assert self._handle is not None
12531267
try:
1254-
if not key.startswith("/"):
1255-
key = "/" + key
12561268
return self._handle.get_node(self.root, key)
1257-
except _table_mod.exceptions.NoSuchNodeError:
1269+
except _table_mod.exceptions.NoSuchNodeError: # type: ignore
12581270
return None
12591271

1260-
def get_storer(self, key):
1272+
def get_storer(self, key: str):
12611273
""" return the storer object for a key, raise if not in the file """
12621274
group = self.get_node(key)
12631275
if group is None:
@@ -1481,7 +1493,7 @@ def error(t):
14811493

14821494
def _write_to_group(
14831495
self,
1484-
key,
1496+
key: str,
14851497
value,
14861498
format,
14871499
index=True,
@@ -1492,6 +1504,10 @@ def _write_to_group(
14921504
):
14931505
group = self.get_node(key)
14941506

1507+
# we make this assertion for mypy; the get_node call will already
1508+
# have raised if this is incorrect
1509+
assert self._handle is not None
1510+
14951511
# remove the node if we are not appending
14961512
if group is not None and not append:
14971513
self._handle.remove_node(group, recursive=True)
@@ -2691,7 +2707,7 @@ def f(values, freq=None, tz=None):
26912707

26922708
return klass
26932709

2694-
def validate_read(self, kwargs):
2710+
def validate_read(self, kwargs: Dict[str, Any]) -> Dict[str, Any]:
26952711
"""
26962712
remove table keywords from kwargs and return
26972713
raise if any keywords are passed which are not-None
@@ -2733,7 +2749,7 @@ def get_attrs(self):
27332749
def write(self, obj, **kwargs):
27342750
self.set_attrs()
27352751

2736-
def read_array(self, key, start=None, stop=None):
2752+
def read_array(self, key: str, start=None, stop=None):
27372753
""" read an array for the specified node (off of group """
27382754
import tables
27392755

@@ -4008,7 +4024,7 @@ def read_coordinates(self, where=None, start=None, stop=None, **kwargs):
40084024

40094025
return Index(coords)
40104026

4011-
def read_column(self, column, where=None, start=None, stop=None):
4027+
def read_column(self, column: str, where=None, start=None, stop=None):
40124028
"""return a single column from the table, generally only indexables
40134029
are interesting
40144030
"""
@@ -4642,8 +4658,8 @@ def _convert_index(index, encoding=None, errors="strict", format_type=None):
46424658
converted,
46434659
"datetime64",
46444660
_tables().Int64Col(),
4645-
freq=getattr(index, "freq", None),
4646-
tz=getattr(index, "tz", None),
4661+
freq=index.freq,
4662+
tz=index.tz,
46474663
index_name=index_name,
46484664
)
46494665
elif isinstance(index, TimedeltaIndex):
@@ -4652,7 +4668,7 @@ def _convert_index(index, encoding=None, errors="strict", format_type=None):
46524668
converted,
46534669
"timedelta64",
46544670
_tables().Int64Col(),
4655-
freq=getattr(index, "freq", None),
4671+
freq=index.freq,
46564672
index_name=index_name,
46574673
)
46584674
elif isinstance(index, (Int64Index, PeriodIndex)):

0 commit comments

Comments
 (0)