3 ms·
Initial thoughts from looking through https://docs.python.org/3/library/typing.html# https://docs.python.org/3/library/typing.html#: 1. Love that it doesn't us
by basil-rash 8y ago
Initial thoughts from looking through https://docs.python.org/3/library/typing.html# https://docs.python.org/3/library/typing.html#:
1. Love that it doesn't use structural typing, NewType seems great.
2. The syntax is bad. Maybe this is a "it just takes getting used to" thing, but I actually find it really bad. In TS, the syntax for typing almost always directly matches the syntax for the rest of the language. In Python, its a weird sort of LISPy DSL think that they made... compare:
Py: Callable[[List[Tuple[int, string]], Dict[string, string]], int]
TS: ([number, string][], { [key: string]: string }) => int
This only gets worse as you chain callables together, whereas in TS everything left-associates as you'd expect and it all works out nicely.
3. Admittedly, the TS dict syntax isn't beautiful, but it becomes very helpful for things like `{ [K in keyof T]: K extends number ? T[K] : never }`, which does not seem to be possible in Py.
4. Related to 3, but no never type? I see NoReturn, but it does not seem to actually cause any errors when you try to assign it to a variable. See below.
5. Type narrowing... does it exist? Seemingly not, see below.
6. Literals as types (enums)?
7. Generics, do I really need to pass in the internal representation of the type I'd like to use? That seems absurd. Will bad things happen if these internal identifiers collide? (Reference: `T = Generic('T')` creates a generic type)
Demo code that should throw an error at the assertUnreachable and nowhere else, but actually throws errors everywhere but the assert unreachable (types seemingly aren't narrowed by `type() == ...` checks):
def foo(x: Union[str, int, float]):
if (type(x) == int):
return x / 3
if (type(x) == str):
return x.upper()
return assertUnreachable()
def assertUnreachable() -> NoReturn:
raise RuntimeError('no way')
(this is all checked using mypy, v. 0.641)
- a1369209993 8y agoRegarding #2, the python code has the arguable advantage that (with appropriate variables in scope) it's valid standard python code[0] that could evaluate to (a representation of) the desired type, whereas the typescript isn't valid javascript code, and I don't think it's a valid (value-level) typescript expression either. 3 and 4 are disappointing though. 0: I'm assuming the extra [ after Callable is a typo.
- basil-rash 8y agoIs there a utility to having your types and your values in the same namespace? The extra [ is not a typo, the syntax is: `Callable[[Arg1Type, Arg2Type], ReturnType]`. Or, if the arguments don't matter, `Callable[..., ReturnType]`, but this does not mean that the type is not a valid expression. Edit: I was missing a ] actually, separating the arguments from the return value.
- a1369209993 8y ago> Is there a utility to having your types and your values in the same namespace? Well somewhat[0], but the main putative benefit would be having types be valid expressions in the target language, since you can do type-checking with function decorators, and generally interact with types useing the normal language mechanism for interacting with values, rather than some horrid bolted-on piece of crap like C++ templates. Server = Tuple[Address,ConnectionOptions] # array subscipt might not the best choice here, but it works UserId = NewType('UserId',int) # ordinary function call Scalar = int | str # could be equivalent to Union[int,str] with appropriate value of Type.__or__ 0: for example: def intBit(N): if N==0: return type(None) if N==1: return Bool if N>INT_WIDTH: return long return int
- basil-rash 8y agomypy's response to that code: error:invalid type comment or annotation note:Suggestion: use intBit[...] instead of intBit(...) So what's really happening is the type expressions are pretending to be "just everyday python", but actually they have arbitrary restrictions (cannot be functions? need to work via overriding `__getitem__`?) that neither you nor I were aware of. This is probably the least "pythonic" implementation possible. And even if the code were valid, it's relying on N being a statically known value, which is a bit off because sure, you could have N be some global const config variable, but it would be very weird for configuring the value of the variable to require you to also go into the code and change things around to work with bool's or None's instead of int's.
- 8y ago
- akubera 8y agoIf you use isinstance(x, (int, float)) instead of type(x) == int then I think you'll find your expected behavior. When you say type narrowing do you mean floats should be automatically interpreted as int? There is typing.{SupportsInt, SupportsFloat} which can be considered "number" base classes which you may consider as type narrowing. Otherwise if you mean "type of x is known in this if-block" you do get that with `isinstance` type checks (which is the preferred, pythonic way). I agree that mypy should warn if a NoReturn is assigned; apparently it just ignores typechecking below the NoReturn function call, and is really only used to ensure the NoReturn function is guaranteed to raise before it returns.
- jakear 8y ago`isinstance` is what I wanted for narrowing, thanks!