Is there a difference between a TypeVar and Any if it is unused. #8257
-
Specifically in a case like this
vs
Is there functionally a difference and what would be considered a better practice if there isnt. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
In general, def func(x: list[Any]):
y = x[0] # y has type Any
y.do_something() # No type error def func[T](x: list[T]):
y = x[0] # y has type T
y.do_something() # Type error I would not recommend using a type variable even in your simple example. A type variable should appear at least twice in a function's signature — typically in both the input signature and the return type. If you find yourself using a type variable in just one place within a signature, that's a sign that you're using a type variable inappropriately or (at best) unnecessarily. |
Beta Was this translation helpful? Give feedback.
Definitely use
Any
, not aTypeVar
. ATypeVar
is unnecessary and confusing at best (and inappropriate and incorrect at worst). TypeVars are also way more expensive for static type checkers to handle because they must gather constraints and then apply those constraints to "solve" the type variable. WithAny
, there is no such work required.