[New-bugs-announce] [issue26477] typing forward references and module attributes

Martijn Pieters report at bugs.python.org
Thu Mar 3 13:07:47 EST 2016


New submission from Martijn Pieters:

Forward references to a module can fail, if the module doesn't yet have the required object. The "forward references" section names circular dependencies as one use for forward references, but the following example fails:

$ cat test/__init__.py
from .a import A
from .b import B
$ cat test/a.py
import typing
from . import b

class A:
    def foo(self: 'A', bar: typing.Union['b.B', None]):
        pass
$ cat test/b.py
import typing
from . import a

class B:
    def spam(self: 'B', eggs: typing.Union['a.A', None]):
        pass
$  bin/python -c 'import test'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/Users/mjpieters/Development/venvs/stackoverflow-3.5/test/__init__.py", line 1, in <module>
    from .a import A
  File "/Users/mjpieters/Development/venvs/stackoverflow-3.5/test/a.py", line 2, in <module>
    from . import b
  File "/Users/mjpieters/Development/venvs/stackoverflow-3.5/test/b.py", line 4, in <module>
    class B:
  File "/Users/mjpieters/Development/venvs/stackoverflow-3.5/test/b.py", line 5, in B
    def spam(self: 'B', eggs: typing.Union['a.A', None]):
  File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python3.5/typing.py", line 537, in __getitem__
    dict(self.__dict__), parameters, _root=True)
  File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python3.5/typing.py", line 494, in __new__
    for t2 in all_params - {t1} if not isinstance(t2, TypeVar)):
  File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python3.5/typing.py", line 494, in <genexpr>
    for t2 in all_params - {t1} if not isinstance(t2, TypeVar)):
  File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python3.5/typing.py", line 185, in __subclasscheck__
    self._eval_type(globalns, localns)
  File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python3.5/typing.py", line 172, in _eval_type
    eval(self.__forward_code__, globalns, localns),
  File "<string>", line 1, in <module>
AttributeError: module 'test.a' has no attribute 'A'

The forward reference test fails because only NameError exceptions are caught, not AttributeError exceptions.

----------
components: Library (Lib)
messages: 261172
nosy: mjpieters
priority: normal
severity: normal
status: open
title: typing forward references and module attributes
versions: Python 3.5, Python 3.6

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue26477>
_______________________________________


More information about the New-bugs-announce mailing list