python / python/cpython

Can't assign entry to `__annotations__` unless a class has existing annotation

Open
#95,532 21 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

topic-typing type-bug
Dominant language
Python
Stars
77.2k
Forks
36k
PR merge metrics
PR metrics pending

Description

Bug report

Can't assign entry to __annotations__ unless a class has existing annotation. This is related to https://github.com/python/cpython/issues/88067.

python 3.9:

Python 3.9.7 | packaged by conda-forge | (default, Sep 29 2021, 20:33:18)
[Clang 11.1.0 ] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo:
...     __annotations__["b"] = int
...
>>> Foo.__annotations__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'Foo' has no attribute '__annotations__'
>>> class Foo:
...     a: int
...     __annotations__["b"] = int
...
>>> Foo.__annotations__
{'a': <class 'int'>, 'b': <class 'int'>}

python 3.10/python 3.11-rc:

Python 3.10.5 (main, Jul 12 2022, 11:32:11) [GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo:
...     __annotations__["a"] = int
...
>>> Foo.__annotations__
{}
>>> class Foo:
...     a: float
...     __annotations__["b"] = int
...
>>> Foo.__annotations__
{'a': <class 'float'>, 'b': <class 'int'>}

Your environment

  • CPython versions tested on: 3.9, 3.10, 3.11-rc
  • Operating system and architecture: Mac, Linux

I'm interested in submitting a PR for this, but first would like to double check that such PR/change would be acceptable?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the class-body examples on the affected Python versions and read the related issue 88067 for the surrounding annotation behavior. Trace how class-level annotations is initialized and verify that assigning an entry in a class with no prior annotations preserves that entry without changing the existing annotated-class behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.