Skip to content

bpo-46644: No longer accept arbitrary callables as type arguments in generics #31159

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,12 @@ class UnionTests(BaseTestCase):
def test_basics(self):
u = Union[int, float]
self.assertNotEqual(u, Union)
with self.assertRaises(TypeError):
Union[int, 42]
with self.assertRaises(TypeError):
Union[int, chr]
with self.assertRaises(TypeError):
Union[int, ...]

def test_subclass_error(self):
with self.assertRaises(TypeError):
Expand Down Expand Up @@ -395,10 +401,6 @@ def test_no_eval_union(self):
def f(x: u): ...
self.assertIs(get_type_hints(f)['x'], u)

def test_function_repr_union(self):
def fun() -> int: ...
self.assertEqual(repr(Union[fun, int]), 'typing.Union[fun, int]')

def test_union_str_pattern(self):
# Shouldn't crash; see http://bugs.python.org/issue25390
A = Union[str, Pattern]
Expand All @@ -411,11 +413,6 @@ def test_etree(self):

Union[Element, str] # Shouldn't crash

def Elem(*args):
return Element(*args)

Union[Elem, str] # Nor should this


class TupleTests(BaseTestCase):

Expand Down Expand Up @@ -2511,6 +2508,8 @@ class ClassVarTests(BaseTestCase):
def test_basics(self):
with self.assertRaises(TypeError):
ClassVar[1]
with self.assertRaises(TypeError):
ClassVar[chr]
with self.assertRaises(TypeError):
ClassVar[int, str]
with self.assertRaises(TypeError):
Expand Down Expand Up @@ -2551,6 +2550,8 @@ def test_basics(self):
Final[int] # OK
with self.assertRaises(TypeError):
Final[1]
with self.assertRaises(TypeError):
Final[chr]
with self.assertRaises(TypeError):
Final[int, str]
with self.assertRaises(TypeError):
Expand Down
95 changes: 47 additions & 48 deletions Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,11 +178,10 @@ def _type_check(arg, msg, is_argument=True, module=None, *, allow_special_forms=
return arg
if isinstance(arg, _SpecialForm) or arg in (Generic, Protocol):
raise TypeError(f"Plain {arg} is not valid as type argument")
if isinstance(arg, (type, TypeVar, ForwardRef, types.UnionType, ParamSpec)):
if isinstance(arg, (type, TypeVar, ForwardRef, types.UnionType, ParamSpec,
_GenericAlias, _SpecialGenericAlias, NewType)):
return arg
if not callable(arg):
raise TypeError(f"{msg} Got {arg!r:.100}.")
return arg
raise TypeError(f"{msg} Got {arg!r:.100}.")


def _is_param_expr(arg):
Expand Down Expand Up @@ -2065,6 +2064,50 @@ class Other(Leaf): # Error reported by type checker
return f


class NewType:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What was the reason to move this definition?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_type_check() was used before defining NewType.

"""NewType creates simple unique types with almost zero
runtime overhead. NewType(name, tp) is considered a subtype of tp
by static type checkers. At runtime, NewType(name, tp) returns
a dummy callable that simply returns its argument. Usage::

UserId = NewType('UserId', int)

def name_by_id(user_id: UserId) -> str:
...

UserId('user') # Fails type check

name_by_id(42) # Fails type check
name_by_id(UserId(42)) # OK

num = UserId(5) + 1 # type: int
"""

__call__ = _idfunc

def __init__(self, name, tp):
self.__qualname__ = name
if '.' in name:
name = name.rpartition('.')[-1]
self.__name__ = name
self.__supertype__ = tp
def_mod = _caller()
if def_mod != 'typing':
self.__module__ = def_mod

def __repr__(self):
return f'{self.__module__}.{self.__qualname__}'

def __reduce__(self):
return self.__qualname__

def __or__(self, other):
return Union[self, other]

def __ror__(self, other):
return Union[other, self]


# Some unconstrained type variables. These are used by the container types.
# (These are not for export.)
T = TypeVar('T') # Any type.
Expand Down Expand Up @@ -2438,50 +2481,6 @@ class body be required.
TypedDict.__mro_entries__ = lambda bases: (_TypedDict,)


class NewType:
"""NewType creates simple unique types with almost zero
runtime overhead. NewType(name, tp) is considered a subtype of tp
by static type checkers. At runtime, NewType(name, tp) returns
a dummy callable that simply returns its argument. Usage::

UserId = NewType('UserId', int)

def name_by_id(user_id: UserId) -> str:
...

UserId('user') # Fails type check

name_by_id(42) # Fails type check
name_by_id(UserId(42)) # OK

num = UserId(5) + 1 # type: int
"""

__call__ = _idfunc

def __init__(self, name, tp):
self.__qualname__ = name
if '.' in name:
name = name.rpartition('.')[-1]
self.__name__ = name
self.__supertype__ = tp
def_mod = _caller()
if def_mod != 'typing':
self.__module__ = def_mod

def __repr__(self):
return f'{self.__module__}.{self.__qualname__}'

def __reduce__(self):
return self.__qualname__

def __or__(self, other):
return Union[self, other]

def __ror__(self, other):
return Union[other, self]


# Python-version-specific alias (Python 2: unicode; Python 3: str)
Text = str

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
No longer accept arbitrary callables as type arguments in generics. E.g.
``List[chr]`` is now an error.
Comment on lines +1 to +2
Copy link
Contributor

@GBeauregard GBeauregard Feb 6, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This patch does not make List[chr] an error. _type_check is not called in this code path.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It does.

>>> List[chr]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/serhiy/py/cpython/Lib/typing.py", line 317, in inner
    return func(*args, **kwds)
           ^^^^^^^^^^^^^^^^^^^
  File "/home/serhiy/py/cpython/Lib/typing.py", line 1126, in __getitem__
    params = tuple(_type_check(p, msg) for p in params)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/serhiy/py/cpython/Lib/typing.py", line 1126, in <genexpr>
    params = tuple(_type_check(p, msg) for p in params)
                   ^^^^^^^^^^^^^^^^^^^
  File "/home/serhiy/py/cpython/Lib/typing.py", line 184, in _type_check
    raise TypeError(f"{msg} Got {arg!r:.100}.")
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Parameters to generic types must be types. Got <built-in function chr>.

Copy link
Contributor

@GBeauregard GBeauregard Feb 6, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That code path is not used in type annotations; try a: List[chr] to reproduce the lack of error. I suppose it can show up in type aliases or get_type_hints, though.

EDIT: I retract this comment, see https://bugs.python.org/msg412662