简体   繁体   中英

Type-hinting a variable to have the same type as another variable in Python

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM