by Timon3 · 3y ago · 0 comments
I strongly disagree. It might be better at some things, but it's much worse at others. Many functions can't be accurately typed (try, for example, to make a well-typed function that concatenates two arbitrary fixed-size tuples), and as far as I know generic type transformations can't be implemented (random example "this type takes a Dict[str, Any] and returns an object with each key turned into a function").
from typing import TypeVar
T, U, V, W = TypeVar('T'), TypeVar('U'), TypeVar('V'), TypeVar('W')
def concatenate(a: tuple[T, U], b: tuple[V, W]) -> tuple[T, U, V, W]:
return a + b
For the generic type transformation example, I'm not sure what you mean: from typing import Any, Callable
Transformer = Callable[[dict[str, Any]], dict[Callable, Any]]
This seems to match your question but it's really weird.Your generic type transformation example also doesn't come close to what Typescript does. The resulting dict will not have known keys based on the keys of the input dict. In Typescript I can write a function that takes an object with known keys, and it returns an object with those same keys having their values mapped to a different type, with the keys still known. I threw together a quick example - just look at the type of resultA/resultB by hovering over the variables[0].
But both are great examples - they are probably the closest you can get in Python, and they are so far removed from the thing I want to represent that they are completely useless.
[0]: https://www.typescriptlang.org/play?#code/MYewdgzgLgBAhjAvDA...
The second example is cool. But I can't find a good practical use case for either example.
If you have a collection that's both heterogeneous and whose [size/key set] is statically known, when would it make sense to apply such generic transformations to them? This sounds like you have tuples or dataclasses where all elements have different meanings (since their types are fixed and different) _and_ you want to treat them like a generic collection _and_ you need the type checker to infer the result type.
The main use of tuples or dataclasses or `NamedTuples` is to pass or return values to/from functions without dealing with long lists of arguments. The elements aren't in the same category, it doesn't make sense to process them as one big collection, they mean different things.
(Also I think you made a mistake in your previous message, you wrote "an object with each key turned into a function" but it's the values that change types here.)
That is exactly what I'm talking about - the size of the tuples is known statically.
> The second example is cool. But I can't find a good practical use case for either example.
There are many interesting use cases in libraries, especially for some of the more esoteric features. Everything can be used for additional type safety.
> If you have a collection that's both heterogeneous and whose [size/key set] is statically known, when would it make sense to apply such generic transformations to them? This sounds like you have tuples or dataclasses where all elements have different meanings (since their types are fixed and different) _and_ you want to treat them like a generic collection _and_ you need the type checker to infer the result type.
Simple example - I have functions that return a Rust-like Result type, and I want to transform that into a different tuple-based format using a decorator. The transformation itself is static, but I can't write one function that handles it all, because Pythons type system is simply not developed enough. Something that would be incredibly easy in Typescript.
> The main use of tuples or dataclasses or `NamedTuples` is to pass or return values to/from functions without dealing with long lists of arguments. The elements aren't in the same category, it doesn't make sense to process them as one big collection, they mean different things.
But I have a use case for exactly this feature. Why should the language limit me? Why should I implement x functions that take different tuple lengths, with me having to choose the correct one for each use case, when I could write one function that does all?
> (Also I think you made a mistake in your previous message, you wrote "an object with each key turned into a function" but it's the values that change types here.)
Sure, though I could also literally write a Map that turns all object keys into functions.
This is wrong. Again, Arbitrary fixed-size tuples are equivalent to structs with an arbitrary amount of properties. Languages shouldn't do this, it destroys the nature of what a TUPLE is which is essentially just a struct with no names.
The concept you are going for is isomorphically encapsulated by ANOTHER type:
List[Any]
You should be using the above type to encode what you want conceptually.That being said if javascript has variadic tuples then it's not a very good type system imo. It encodes redundant concepts. Why have a tuple with Variadic arguments when I have Arrays that do the exact same thing?
Okay, that might be your personal feelings on the topic. But do you understand the concept of "generic functions"? Sometimes you have to apply generic transforms to data. Being able to correctly express your transformations in a type system isn't "wrong", it's useful.
> List[Any]
Sorry, but I really think you don't understand what I'm talking about. If I write a function that handles tuples of arbitrary length and that function returns a transformed version of that tuple, I keep the information about individual tuple elements. This is thrown away in a list.
> That being said if javascript has variadic tuples then it's not a very good type system imo. It encodes redundant concepts. Why have a tuple with Variadic arguments when I have Arrays that do the exact same thing?
Arrays don't do the same thing, so they are not redundant concepts. Tuples have elements in specified positions with specified types. Arrays have one type (possibly a union type) over many elements.
No, you can type variable-length tuples in Python. A variable int tuple, for example, can be typed as Tuple[int, ...].
You can't concatenate two variable-length tuples, which makes sense - where would the cutoff be? But you should absolutely be able to concatenate two fixed-size tuples, and it's very limiting that you can't.
I don't thing variadic generics support is supported in most statically typed languages. The only one I can think of right now that supports this is C++.
[0] https://www.typescriptlang.org/play?#code/C4TwDgpgBAglC8UDaA...
from typing import TypeVarTuple
Ts = TypeVarTuple("Ts”)
Us = TypeVarTuple("Us”)
def tconcat(
t1: tuple[*Ts],
t2: tuple[*Us]
) -> tuple[*Ts, *Us]: ...A Tuple is Typed as something as a Fixed size. That's right, it's like this at the Type level. The entire concept of a tuple is a Product type or essentially like a struct but with no names for each parameter.
Tuple[int, str, float] #correct
Doing what you're doing here is equivalent to creating a Struct with variadic properties.If you want some container that holds an arbitrary amount of things that is a List
The correct type for what you want is actually this:
List[Any]That's backwards. It doesn't work (as noted in GP, because Python supports unpacking only a single variadic parameter in a type annotation), but it does capture the nature of a tuple.
It is (or, more precisely, would be, if the syntactic limitation was relaxed to allow it) a generic function that operates on two tuples of arbitrary tuple types and returns a tuple of a third tuple type whose shape is a simple concatenation of the shapes of the input tuples.
> Doing what you're doing here is equivalent to creating a Struct with variadic properties.
Well, a "struct" in Python is a particular low-level byte-mapped datatype, but the generic concept of a Struct differs from a tuple in two ways -- fields identified by name and that Structs are generally mutable.
> If you want some container that holds an arbitrary amount of things that is a List
But... I don't want that, and that's not what this works on.
There's a difference between a function that works on containers of changeable length and a generic function that works on immutable containers (so, fixed length and contents), but is adaptable to any length (or more specifically, shape, including not only length by order of types of elements) of arguments, producing a result of a container type whose shape is strictly determined by the shapes of the inputs, with the shapes statically verifiable.
Python is very close to allowing that, which is very different than:
def concat(l1: list, l2: list) -> list: ...
which is a fine function, but not at all what the other one is about.This isn't definable without dependent types or a concat operator at the type level. Dependent types aren't a thing we are talking about here and languages that support this feature are waaay out of scope.
You're basically asking for stuff like this:
func concat(a: Array[int; M], b Array[int; N]) -> Array[int; N + M]
or func concat(a: Tuple[*args1], b Tuple[*args2]) -> Array[*(args + args)]
Which is bringing those programming terms up a level into types. This doesn't exist in the realm of programming we're talking about. Idris, Lean and Coq are more you're game here and those languages are clearly off topic.>But... I don't want that, and that's not what this works on.
You want something well out of scope of this conversation and well out of scope of most practical programming languages. You still don't get what a tuple is. Nobody defines a Product type with an arbitrary amount of properties anymore then someone defines a struct with an arbitrary amount of properties anymore then they would do it for a tuple.
This is NOT the definition of a tuple. People are confusing the Tuple for some Immutable list.
>Python is very close to allowing that, which is very different than:
Python shouldn't allow this, neither should TS. If typescript allows it, it's probably some arbitrary shortcut feature. Dependent types at the type level supported in a very generic way is very very unlikely.
Like you people are trying to explain to me what a generic is while doing all kinds of programming operations on type level entities like concatenating them and combining shapes. Is the concat the only way to do it? What about an intersection? These operators only come into play with advanced theoretical langauges like Lean or Idris and it's very off topic.
And I have no idea why you claim that a list is "correct".
Read my other reply to you to see the problem of taking functions with "generic" number of parameters. What are you going to do with each parameter? What are the types of each parameter? You can't do anything other then breaking out of the type system. Basically you're filling those tuples with a bunch of "Any" types. So what's the point of the type system now? There is No point. Just like List[Any]
To get your idea to work you need dependent types.
It's a shame, because it makes features like decorators significantly harder to use with static typing.
The definition for tuples here is similar to a struct.
They are one in the same except structs have names for each property while tuples don't. That is literally the main concept of a tuple, just a struct with no names for properties.
The type system for python is already "there", it is in fact superior to many other type systems from other popular languages.
No, it wouldn't.
It would be equivalent to creating a generic type where the concrete types that would be compatible with it would be structs of different shapes.
But if you use the same variadic type within a particular context (e.g., a function signature and definition), then any given call to the function, that variadic type must represent the same concrete type each place.
def concat_tuples(tuple1: Tuple[int, str, float], tuple2: Tuple[str, str, str]) -> Tuple[int, str, float, str, str, str]:
return tuple1 + tuple2
Your second function you just broke out of the type system with Any. Give me a more exact, are you saying Any is a constrained type variable? The only possibility here is this: T = TypeVar('T')
def transform(x: Dict[str, T]) -> Dict[str, Callable[[], T]]:
return {key: lambda : value for key, value in x.items()}
If you want that lambda to do something else you have to constrain T. Constraining T will give me more options in the definition: from numbers import Number
def transform2(x: Dict[str, Number]) -> Dict[str, Callable[[Number], Number]]:
return {key: lambda y: value + y for key, value in x.items()}
def transform3(x: Dict[str, Number]) -> Dict[str, Callable[[], Number]]:
return {key: lambda: value + value for key, value in x.items()}
etc...The thing is because these type checkers are external, anyone can add arbitrary features to them and extend it. Someone can make it to the level of proof checking... eliminating the need for testing in general. Of course the syntax has to support it too.
I specifically talked about arbitrary tuples. Your function only handles specific tuples.
> Your second function you just broke out of the type system with Any. Give me a more exact, are you saying Any is a constrained type variable?
I'm not sure what you're trying to say here. Yes, you can implement the function, I never claimed otherwise. I'm talking about the _type system_.
> The thing is because these type checkers are external, anyone can add arbitrary features to them and extend it.
The type system is a core feature of Python. Until it supports what I want, I can't really use what I want with Python.
The type constrains the definition. Look at the definition, there is ONLY one possible definition when converting this:
Dict[str, T] -> Dict[str, Callable[[], T]]
Literally. Try to think of another way to define the lambda, you can't. The more open the type the more constrained the definition the more constrained the type the more open the definition.> I specifically talked about arbitrary tuples. Your function only handles specific tuples.
I remarked on this in other replies. How will you define the return value of the concat and have it exactly type correct? It's not possible bro. You can't do much with tuples of arbitrary types. Not unless you have dependent types.
>The type system is a core feature of Python. Until it supports what I want, I can't really use what I want with Python.
Type checking in python is an external application. The interpreter doesn't do any type check. Type checking is achieved by running another program. All kinds of additional features and custom interpretations on types can be inserted into these type checkers.
Yes, and if Python had a better type system, I could write a more concrete definition. Why don't you understand that?
> I remarked on this in other replies. How will you define the return value of the concat and have it exactly type correct? It's not possible bro. You can't do much with tuples of arbitrary types. Not unless you have dependent types.
Of course it's possible, the type system even supports almost everything that's necessary. You can already define what I want with a single fixed-size tuple of arbitrary size, you just can't do it with multiple ones. Why do you have this strange fixation on calling this "wrong" and "impossible"?