Tinche / tightwrap

A type-safe `functools.wraps`.
Apache License 2.0
17 stars 1 forks source link

`NameError: name 'FilePath' is not defined` when trying to wrap `pandas.read_csv`. #6

Open rudolfbyker opened 14 hours ago

rudolfbyker commented 14 hours ago
from pandas import read_csv
from tightwrap import wraps

@wraps(read_csv)
def my_read_csv(*args, **kwargs):  # type: ignore[no-untyped-def]
    return read_csv(*args, **kwargs)

if __name__ == "__main__":
    df = my_read_csv("data.csv")

This causes the following error at runtime:

Traceback (most recent call last):
  File "test.py", line 5, in <module>
    @wraps(read_csv)
     ^^^^^^^^^^^^^^^
  File "venv\Lib\site-packages\tightwrap\__init__.py", line 40, in wrapper
    orig_sig = _get_resolved_signature(wrapped)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "venv\Lib\site-packages\tightwrap\__init__.py", line 20, in _get_resolved_signature
    evaluated_annotations, fn_globals, fn_locals = get_annotations(fn)
                                                   ^^^^^^^^^^^^^^^^^^^
  File "venv\Lib\site-packages\tightwrap\_backported.py", line 85, in get_annotations
    return_value = {
                   ^
  File "venv\Lib\site-packages\tightwrap\_backported.py", line 86, in <dictcomp>
    key: eval_if_necessary(value, obj_globals, obj_locals)
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "venv\Lib\site-packages\tightwrap\_backported.py", line 17, in eval_if_necessary
    return eval(source, globals, locals)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<string>", line 1, in <module>
NameError: name 'FilePath' is not defined

I'm using pandas 2.2.3 and tightwrap 24.3 .

Tinche commented 12 hours ago

Hm, pandas uses an if TYPE_CHECKING: block to import FilePath, so we can't inspect the read_csv function.

Maybe we can be smarter about getting the return type from the function and avoiding looking at the arguments.