Just noticed my Python 3.13 interpreter accepts the following syntax:
>>> x
(1, 2, 3)
>>> y = set[x]
>>> y
set[1, 2, 3]
>>> y = set[1,2,3]
>>> y
set[1, 2, 3]
>>> d = dict[1,2,3]
>>> d
dict[1, 2, 3]
>>> type(d)
<class 'types.GenericAlias'>
I am wondering if this a valid syntax, and if so, then what is the use and interpretation of it?
Just noticed my Python 3.13 interpreter accepts the following syntax:
>>> x
(1, 2, 3)
>>> y = set[x]
>>> y
set[1, 2, 3]
>>> y = set[1,2,3]
>>> y
set[1, 2, 3]
>>> d = dict[1,2,3]
>>> d
dict[1, 2, 3]
>>> type(d)
<class 'types.GenericAlias'>
I am wondering if this a valid syntax, and if so, then what is the use and interpretation of it?
Types that define the __class_getitem__
method can be "indexed" to support generic types; the method itself returns an instance of types.GenericAlias
which at runtime can be treated the same as the type itself (as generic typing is only of interest to static type checkers). Some examples:
>>> s = set[3]
>>> type(s)
<class 'types.GenericAlias'>
>>> s([1,2,3])
{1, 2, 3}
This works because the GenericAlias
remembers both the type used to create it and the arguments passed to __class_getitem__
:
>>> s.__origin__
<class 'set'>
>>> s.__args__
(3,)
This ability comes from the syntax used for type annotations. Collection type names can be subscripted to specify the types of the elements of a collection, e.g.
set_of_ints = set[int]
myset: set_of_ints = {1, 2, 3}
Your use doesn't actually make sense because x
is not a type name. But the Python runtime doesn't do any type validation, so it doesn't care. It just checks the syntax, and syntactically set[x]
is analogous to set[int]
. You'd probably get an error if you tried to validate your code with a type checker like mypy
.