New submission from Ruairidh MacLeod <[email protected]>:
When incorrectly defining a function with a typed List[T] argument where T is a
tuple instance, a TypeError is correctly raised:
t = (1,)
def f(a: List[t]): ...
# => TypeError: Parameters to generic types must be types. Got 1.
When t is an instance of a tuple subclass though, and one of its items is an
empty string, a SyntaxError is raised instead in the typing module:
class T(tuple):
def __new__(cls):
return tuple.__new__(cls, ("",))
t = T()
def f(a: List[t]): ...
# => SyntaxError: Forward reference must be an expression -- got ''
Full stack trace:
Traceback (most recent call last):
File "/opt/python37/lib/python3.7/typing.py", line 449, in __init__
code = compile(arg, '<string>', 'eval')
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "test.py", line 5, in <module>
def f(a: List[call]):
File "/opt/python37/lib/python3.7/typing.py", line 254, in inner
return func(*args, **kwds)
File "/opt/python37/lib/python3.7/typing.py", line 631, in __getitem__
params = tuple(_type_check(p, msg) for p in params)
File "/opt/python37/lib/python3.7/typing.py", line 631, in <genexpr>
params = tuple(_type_check(p, msg) for p in params)
File "/opt/python37/lib/python3.7/typing.py", line 132, in _type_check
return ForwardRef(arg)
File "/opt/python37/lib/python3.7/typing.py", line 451, in __init__
raise SyntaxError(f"Forward reference must be an expression -- got {arg!r}")
SyntaxError: Forward reference must be an expression -- got ''
Lastly, a different TypeError is raised for an empty subclass:
class C(tuple): ...
c = C()
def f(a: List[c]): ...
# => TypeError: Too few parameters for typing.List; actual 0, expected 1
This exception behavior seems inconsistent, although it's definitely a minor
issue.
----------
components: Interpreter Core
messages: 368554
nosy: rkm
priority: normal
severity: normal
status: open
title: Inconsistent exceptions caused by typing + tuple subclasses
type: behavior
versions: Python 3.9
_______________________________________
Python tracker <[email protected]>
<https://bugs.python.org/issue40582>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com