1

Can I use a typed function definition from one stub file in another? E.g., I have my __init__.pyi and also extractor.pyi.

We want to reference some methods from extractor.py, so we keep compatibility and not redefine types.

In extractor.pyi I have:

def _func(arg: str) -> str: ...

Now I use in __init__.pyi:

from .extractor import _func

However, my linter is complaining.

Is it, in general, possible to import stubs from other .pyi files? If yes, how should I do it correctly?

Alex Waygood
  • 6,304
  • 3
  • 24
  • 46
Beliaev Maksim
  • 968
  • 12
  • 21
  • What linter are you using? what is the error? – David Culbreth Aug 30 '21 at 15:41
  • @DavidCulbreth, mypy, error: Module has no attribute "_func" [attr-defined]. Overall Python code works, but only mypy complaints – Beliaev Maksim Aug 30 '21 at 15:43
  • sometimes the properties that are prefixed with a single underscore can be considered "private"-ish in python. you should make sure that `mypy` doesn't treat them that way. Optionally: rename the function to something else (like `func`) and see if you still have the error – David Culbreth Aug 30 '21 at 15:56
  • It seems to me this might be exclusively related to imports. Please provide the project structure and check [this question/answer](https://stackoverflow.com/questions/16981921/relative-imports-in-python-3) about relative imports. Moreover, the type annotation most likely have nothing to do with the issue. – MatBBastos Aug 30 '21 at 15:57
  • It could also be configuration issue in mypy standard paths. It might not be 'looking' for files in the path where your `extractor.py` is, which leads to it not understanding that it has a reference there. – MatBBastos Aug 30 '21 at 15:59
  • Do you need to? I thought that `mypy`, if it needed any type information for something imported from `extractor.py`, would know to look in `extractor.pyi` automatically, without `__init__.pyi` having to know anything about `extractor.py` or `extractor.pyi`. – chepner Aug 30 '21 at 16:06
  • do not think it is related to imports, since in general code and all test work. Here is a commit: https://github.com/getsentry/responses/pull/397/commits/eaea4d5b2c3aa7e8d87e5e75d8a6b8d56b8ee9e1 Issue is on line 1310 – Beliaev Maksim Aug 30 '21 at 20:59
  • since json_params_matcher is imported into the module for compatibility, it is not typed. However I typed it in parent file. But linter complains. Thus, I am not sure that what I do is a good practice – Beliaev Maksim Aug 30 '21 at 21:00

0 Answers0