pythonpython-typingpyright

How to assign a type hint from the return type hint of a function


I'm using an API that uses type hints returned from functions to store information (I know that this is not recommended, I have no control over the API):

my_hint: StringProperty()

This works, but it removes the ability to use the type hint as an actual type hint.

I'm looking for a way to create a wrapper that would maintain the same syntax as the above example, but when type hinting, would assign a different, more useful type (in this case a str type).

My first idea was to do something like this:

if typing.TYPE_HINTING:
    def StringProperty() -> str: pass

my_hint: StringProperty()

However, this doesn't work, with my_hint instead being assigned the Any type.

Is there a way to do this, keeping in mind that I can't change the way the API works?


Solution

  • (Based on a comment of yours, I assume you are using Pyright/Pylance on VSCode.)

    Here's my recommendation: Forgo static type checking altogether.

    StringProperty() is a call expression, which will not be recognized as a valid annotation expression by spec-compliant type checkers (including Pyright) no matter what you do at runtime.

    All non-type-hint uses of the name: expression syntax are not recommended. The library/framework in question made an uncommon and unfortunate choice.