Home > Blockchain >  How to add type hints for an inner or nested function inside the stub file
How to add type hints for an inner or nested function inside the stub file

Time:06-17

How to add type hints for an inner function (or nested function) inside the stub file?

code in parsable_base.py

class TemplateBase:
    def copy(self, _parent=None):
        def walk_properties(template_based):
            for prop_holder in template_based.properties.values():
                if isinstance(prop_holder.prop, TemplateBase):
                    walk_properties(prop_holder.prop)
                elif isinstance(prop_value, PrimitiveBase):
                    value_copies[prop_value] = prop_value.copy()
                else:
                    references.append(prop_value)

        value_copies = {}
        references = []
        walk_properties(self)

code in parsable_base.pyi

class TemplateBase(ParsableBase):
    def copy(self: _T, _parent=...) -> _T: ...

I would like to add a type hint (TemplateBase) for argument template_based in the inner function walk_properties.

I know I can add it in the code file (parsable_base.py) like:

        def walk_properties(template_based: TemplateBase) -> None:

But I would like to keep my code file clean and add it in the stub file (parsable_base.pyi). I would think it would be something like:

class TemplateBase(ParsableBase):
    def copy(self: _T, _parent=...) -> _T:
        def walk_properties(template_based: TemplateBase) -> None: ...

But my IDE (PyCharm) doesn't recognise it so I think it's wrong.

How do I do it properly.

parsable_base.py and parsable_base.pyi are in the same folder (package).

CodePudding user response:

I believe this is a minimal version of the issue you are facing:

class A:
    def func(self, var: A) -> None:
        ...

Which produces:

Traceback (most recent call last):
  File "...\72658624.py", line 2, in <module>
    class A:
  File "...\72658624.py", line 3, in A
    def func(self, var: A) -> None:
NameError: name 'A' is not defined

This issue can be solved by importing annotations from __future__:

from __future__ import annotations

class A:
    def func(self, var: A) -> None:
        ...

Now it compiles properly. See PEP 563 for more information. In short, this allows type hints for names that have not been defined yet. As you can guess, when Python parses the file, the class A has not been fully defined yet when it encounters var: A, causing the issue.

CodePudding user response:

A nested function is not a part of the API as it's inaccessible (for example trying to typehint a random variable under a function would act the same), so a stub file can't document it.

If the library is your own, I'd recommend simply doing typing in the Python file

  • Related