4 ms·
> Similarly where a language with first-class support for types might have `type Foo<T>`, Python makes you write `T = TypeVar("T"); class Foo(Generic[T])` or so
by codethief 5y ago
> Similarly where a language with first-class support for types might have `type Foo<T>`, Python makes you write `T = TypeVar("T"); class Foo(Generic[T])` or something like that, and it gets more confusing when you only want one of the methods to be generic and I can never remember whether that `T` takes on a single type across all uses or which scope I need to define it in, etc.
I don't know about you but I find PEP 484 very clear here: https://www.python.org/dev/peps/pep-0484/#scoping-rules-for-type-variables https://www.python.org/dev/peps/pep-0484/#scoping-rules-for-...
- staticassertion 5y agoThe PEP is clear, it's just extremely unintuitive that, within the scope of declaration, a type T can be many different types.
- throwaway894345 5y agoFair enough. Maybe I didn't come across that at the time or perhaps it's been since revised. Even still, it's a poor substitution for the more familiar / intuitive `class Foo[T]:` / `def foo[T](...)` style.
- codethief 5y agoHmm it might take some getting used to but I've actually found it quite straight-forward to comprehend and reason about. The nice thing is that, since TypeVars are ordinary variables, you can re-use them / import them in multiple modules and avoid a lot of boilerplate code.
- throwaway894345 5y ago> The nice thing is that, since TypeVars are ordinary variables, you can re-use them / import them in multiple modules and avoid a lot of boilerplate code. Maybe I'm missing something, but the boilerplate only exists because Python makes you define them as ordinary variables in the first place. So while you can have a `foo.py` file like this: T = TypeVar("T") And a `bar.py` file like this: from foo import T class Bar(Generic[T]): ... So are you saying that this is less boilerplate than a `bar.py` that just defines its own `T` TypeVar? Because that seems like a pretty comparable amount of boilerplate. Or are you saying that it's less boilerplate than languages that don't treat TypeVars as ordinary variables, e.g., Rust? Because in Rust our `bar.rs` file would look like this: `struct Bar<T> {...}` (and the scoping rules are patently obvious, to boot).
- codethief 5y agoNo, in this particular example, there's no real advantage. What I meant were situations where the TypeVar gets a little more complicated, compare the additional parameters on https://docs.python.org/3/library/typing.html#typing.TypeVar https://docs.python.org/3/library/typing.html#typing.TypeVar . Then importing TypeVars starts to pay off because you only have to define your bounds etc. once.
- throwaway894345 5y agoAh, that makes sense. Thanks for clarifying.