[New-bugs-announce] [issue40583] Runtime type annotation mutation leads to inconsistent behavior

Saumitro Dasgupta report at bugs.python.org
Sun May 10 03:40:57 EDT 2020


New submission from Saumitro Dasgupta <ethereon at gmail.com>:

Adding type annotations at runtime may lead to inconsistent results. Consider the following example:

    class Base:
        base: int

    class Alpha(Base):
        pass

    class Beta(Base):
        foobar: int

    # Case 1: This mutates Base's __annotations__
    Alpha.__annotations__['injected'] = bool
    assert Alpha.__annotations__ is Base.__annotations__

    # Case 2: This mutates Beta's own copy of __annotations__
    Beta.__annotations__['injected'] = bool

Such mutations of __annotations__ seem to be perfectly legal (https://www.python.org/dev/peps/pep-0526/#runtime-effects-of-type-annotations).

However:
1. In case 1, this leads to the accidental mutation of Base's annotations. Not entirely certain if that's expected, but seems undesirable.

2. There are further differences when looking at `__dict__['__annotations__']`: for Alpha, there is no __annotations__ entry in __dict__. However, for Beta, it's set to `{'foobar': <class 'int'>, 'injected': <class 'bool'>}`. This discrepancy leads to further inconsistent results. In particular, when transforming these classes to dataclasses, which specifically looks at __dict__['__annotations__'](https://github.com/python/cpython/blob/3.8/Lib/dataclasses.py#L856). Converting Alpha to a dataclass leads to no fields. Converting Beta to a dataclass leads to two fields (foobar and injected).  It's worth noting that typing.get_type_hints produces reasonable results here.

----------
components: Interpreter Core, Library (Lib)
messages: 368569
nosy: Saumitro Dasgupta
priority: normal
severity: normal
status: open
title: Runtime type annotation mutation leads to inconsistent behavior
type: behavior
versions: Python 3.8

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue40583>
_______________________________________


More information about the New-bugs-announce mailing list