From variable name to type hint

1.3k views Asked by At

Is there a way to define a type hint via the variable name?

Example:

Everytime I name a variable response in my code, I want it to have a type hint to django.http.HttpResponse.

My use case is type hinting for IDEs like PyCharm. Up to now I have no use case to evaluate this at run-time.

I would like to have general (as opposed to pycharm specific) solution.

I want to avoid doing manual and explicit type hinting over and over again.

Please tell me why you down-vote this question. I am curious and willing to learn.

3

There are 3 answers

1
guettli On BEST ANSWER

Add type annotations to all methods which return a HttpResponse

A variable in Python needs to declaration. It gets created by being a lvalue (my definition, maybe there is a better way to describe this)

response=handle_request(request)

If handle_request() has a type annotation, then there is no need to do type annotation for response.

This does not answer the question directly, but solves the problem behind the question.

This answer is based on the comment of user Alex. Thank you :-)

0
guettli On

Add type annotation to all first usages of response

def test_foo():
    response: django.http.HttpRequest
    response=handle_request(request)

See https://www.python.org/dev/peps/pep-0526/

This has the drawback that response: django.http.HttpRequest needs to be put before each first usage in a scope. AFAIK there is no way to define this only once per module level

2
guettli On

Add type hints via auto-generated stub files

You can auto-generate create stub files (with .pyi extension) which contain type hints for the source code.

I guess this auto-generating is not difficult to implement.

This has the benefit to the answer called "Add type annotation to all first usages of response", that the source code does not contain the same line (response: django.http.HttpRequest) several times

Drawback: you need a build-step to create the stub files.