Albert
Albert

Reputation: 68310

PyCharm / Python docstring return type hint for locally imported class

I want to define a rtype in the docstring, using a class which is not imported globally in the module (because I cannot do that, because of circular imports).

I.e. like this:

def get_engine():
   """
   :rtype: sisyphus.localengine.LocalEngine
   """
   from sisyphus.localengine import LocalEngine
   return LocalEngine()

sisyphus is a package, and sisyphus.localengine a module in that package. I registered the parent directory of sisyphus as the source root directory in PyCharm.

This does not seem to work. At least PyCharm (2018.2.4) shows the type hint () -> Any for this function.

If I remove the rtype hint, it shows the correct hint () -> LocalEngine, so the audio-detection works (if I don't want to explicitly specify it).

How do I correctly specify the rtype hint such that this works?

Upvotes: 1

Views: 814

Answers (1)

Marcel Wilson
Marcel Wilson

Reputation: 4572

Assuming you're in python >=3.5, you can use forward references in type hinting.
See also this jetbrains blog post.

def foo() -> 'sisyphus.localengine.LocalEngine':
    ...

Upvotes: 1

Related Questions