Repository navigation
Bug - Type aliases in closure does not work #8273
Description
Activity
- changed the title
[-]Feature - Type aliases in closures don't work[/-][+]Bug - Type aliases in closures don't work[/+]on Jan 11, 2020 - changed the title
[-]Bug - Type aliases in closures don't work[/-][+]Bug - Type aliases in closure does not work[/+]on Jan 11, 2020 - addedbugmypy got something wrongmypy got something wrong
on Jan 13, 2020 Here is a simplified example that shows the root cause of the unexpected behavior:
from typing import TypeVar, Callable T = TypeVar('T') F = Callable[[T], T] def f() -> F[T]: ... def g() -> Callable[[T], T]: ... reveal_type(f) # def [T] () -> def (T`-1) -> T`-1 reveal_type(g) # def () -> def [T] (T`-1) -> T`-1
The scope (?) of the type variable is wrong when using a type alias. The type of
fshould be the same as the type ofg.I've investigated this for a little while. For case like
from typing import TypeVar, Sequence T = TypeVar('T') S = Sequence[T] def f() -> S[T]: ... def g() -> Sequence[T]: ...
T gets bound to the function after
semanal/analyze_func_def:update_function_type_variables, and then whenS[T]get analyzed, T will get a binding from the function scope. Therefore, in this issue, the type variable is bound to the function instead of the aliased callable. To proper fix this issue involves at least two major steps:- Update
semanal/update_function_type_variablesto explicitly handle TypeAlias when its target is a callable. Currently, I modifytypeanal/visit_unbound_typeand mimic the behavior when encountering a callable. This part seems OK. - Analyze function signature, bind
T. However,Callable[[T], T]is specially handled while TypeAlias go through a more generic expanding approach.
That's all I've gone so far and some insights, either high-level abstraction or low-level details would help a lot on fixing this @JukkaL
- Update
Definitely been feeling the pain of this one lately. Long type annotations (that could otherwise be broken up type aliases) are really inhibiting code readability. Anyone know of good workarounds for this?
- addedtopic-type-aliasTypeAlias and other type alias issuesTypeAlias and other type alias issuestopic-callsFunction calls, *args, **kwargs, defaultsFunction calls, *args, **kwargs, defaults
on Apr 4, 2022 Closing as a duplicate of #3924
This may be a known limitation of the type system, but it would be nice if it were possible to write the following without the commented error:
In order for this to work correctly I have to replace the type alias
Decoratorwith the explicitCallable[[F], F]. This is trivial to change in this case, but for more complex types this would inhibit readability greatly.Details:
What version of MyPy: 0.761
Have you tried on master: no
Are there any flags engaged: no