Can I re-export a type from a different Python type stub file?

Viewed 409

I am writing type stubs for a proprietary Python platform. The platform often defines classes in some modules and re-export them from other modules. I need my type stubs to reflect that the type exists in more than one file.

For example

_foo.py:

class SomeType:
    # Implementation here

foo.py:

from _foo import SomeType

How do I write type stubs for these files?

I have tried this:

_foo.pyi:

class SomeType:
    ...

foo.pyi:

from _foo import SomeType

But it doesn't work, mypy throws this error:

error: name 'foo.SomeType' is not defined

Is there a way to make this work without copy-pasting the type stub into both files?

2 Answers

Please check out the import section of type stub document, it should provide the answer for what you needed.

__all__ is actually useful if you want to export private variables / types (prefixed with underscore). If you really don't like that, you can use the import as form:

from _foo import SomeType as SomeType

It guarantees SomeType to be re-exported.

After some trial and error, I noticed this works:

foo.pyi:

from _foo import SomeType

__all__ = ["SomeType"]

I am not thrilled with this though, as it looks like it could have side effects, but for now it works.

Related