Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type aliases at function scope does not work as expected #5769

Closed
martin-ejdestig opened this issue Oct 11, 2018 · 7 comments
Closed

Type aliases at function scope does not work as expected #5769

martin-ejdestig opened this issue Oct 11, 2018 · 7 comments

Comments

@martin-ejdestig
Copy link

The following code:

from typing import Dict

def foo(text: str) -> str:
    Bar = str
    Baz = Dict[Bar, int]
    return ''

Results in mypy0.630 reporting 'error: Invalid type "Bar"'.

If Bar is moved to file scope, there are no warnings.

@ilevkivskyi
Copy link
Member

This is actually by design. At nested scopes, such as class or function, assignments with a class object in the r.h.s. create a variable with type Type[...] instead of an alias. The reason is that this is much more typical use case. Note that a subscripted assignment like Baz = Dict[str, int] still creates an alias.

There is a long overdue documentation issue about this #3494, and also about the extra-terse error message #4030. I will raise priorities of both to high.

@martin-ejdestig
Copy link
Author

It is very confusing though.

I am also wondering, is there a way to create an alias for str at local scope like in this example? Do not want to pollute the outer namespace.

@ilevkivskyi
Copy link
Member

Why do you need create an alias to str? Maybe what you want is a NewType actually?

@martin-ejdestig
Copy link
Author

For readability. Did not know about NewType, will try to use that instead.

@martin-ejdestig
Copy link
Author

martin-ejdestig commented Oct 12, 2018

NewType worked. Thank you. (Had to convert str to Baz in a couple places but I guess I gained a bit of type safety.)

Would like to reiterate that it is still very confusing though. Especially since just moving Bar to file scope works. Documentation and better error message will help, but it is still not intuitive.

@ilevkivskyi
Copy link
Member

Would like to reiterate that it is still very confusing though.

Just stating this is not very helpful, what is the solution that you propose?

@martin-ejdestig
Copy link
Author

I know too little about how mypy relates to Python and the language specification. I assume it is too late to change so that "Bar = str" means the same thing at file and function scope? Or is that something that can be done?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants