Reputation: 602
Example:
def f(...): ...
v: type(f) = decorate(f)
But VSCode's Python Language Server doesn't seem to recognize it (and MyPy gives it object
type?).
Part of the problem here is that decorate
is not manually typed and is improperly inferred.
Upvotes: 3
Views: 866
Reputation: 30151
Type expressions are evaluated statically by the type checker.* Complicated expressions such as type(f)
are not guaranteed to work, because type(f)
evaluates to the runtime type of f
, not its statically annotated value.** The type checker does not know what that runtime type will be. In general, you should stick to the type expressions described in PEP 484 for maximum compatibility.
Part of the problem here is that
decorate
is not manually typed and is improperly inferred.
So fix it. For example, you could say that it returns an object of the same type as its argument:
T = typing.TypeVar('T')
d = typing.cast(typing.Callable[[T], T], decorate)
v = d(f) # v is inferred to have the same type as f
* Type expressions are also evaluated at runtime, stored in the __annotations__
field, and then never used again unless some code decides to introspect them. This runtime functionality is rarely used and not relevant to the question.
** In fact it's worse than that, because someone might have monkey-patched your module with a custom type()
that does something completely different from the builtin.
Upvotes: 3