Skip to content

Fixed TypedAttributeSet rejecting its own subclasses - #1358

Merged
agronholm merged 13 commits into
agronholm:masterfrom
pasmud:gsz/fix-typedattr-set-inherited-annotations
Oct 20, 2026
Merged

agronholm merged 13 commits into
agronholm:masterfrom
pasmud:gsz/fix-typedattr-set-inherited-annotations

Conversation

@pasmud

@pasmud pasmud commented Sep 28, 2026

Copy link
Copy Markdown
Contributor

Changes

Fixes #.

TypedAttributeSet.__init_subclass__() compared every public name in dir(cls) against
cls.__annotations__. Since Python 3.10, __annotations__ only ever contains the
annotations declared in the class itself, never the inherited ones, so every attribute
inherited from a base class was reported as missing its type annotation:

>>> class MyTypedAttribute(TypedAttributeSet):
...     string_valued_attribute: str = typed_attribute()
>>> class MyOtherTypedAttribute(MyTypedAttribute):
...     some_float_attribute: float = typed_attribute()
TypeError: Attribute 'string_valued_attribute' is missing its type annotation

That made subclassing a typed attribute set impossible, even though the class docstring
says the check applies to "every public attribute of every subclass", and extending the
documented providers and attribute sets is the natural way to use the typed attribute
system. It only went unnoticed because all three built-in sets (SocketAttribute,
FileStreamAttribute, TLSAttribute) declare every public attribute directly.

The check now gathers the annotations across the whole MRO. The attributes a class
declares itself are still required to be annotated, and the built-in sets are unaffected.

The annotations are collected without being evaluated, so unlike get_type_hints() this
does not require the annotation names to be resolvable at class creation time, which
would otherwise turn an unresolvable forward reference into a NameError.

Checklist

  • You've added tests (in tests/) which would fail without your patch
  • You've updated the documentation (in docs/), in case of behavior changes or new
    features
  • You've added a new changelog entry (in docs/versionhistory.rst).

pasmud and others added 3 commits September 28, 2026 15:29
TypedAttributeSet.__init_subclass__() compared every public name in
dir(cls) against cls.__annotations__. On Python 3.10 and later,
__annotations__ only ever contains the annotations declared in the class
itself, so any attribute inherited from a base class was reported as
"missing its type annotation". This made subclassing a typed attribute
set impossible, even though the class docstring states that the check
applies to "every public attribute of every subclass", and the typed
attribute system is built around wrapping and extending the documented
providers and attribute sets.

The check now gathers annotations across the whole MRO. Attributes that
a class does declare itself are still required to be annotated, and the
three built-in sets (SocketAttribute, FileStreamAttribute, TLSAttribute)
are unaffected since they declare every public attribute directly.

The annotations are collected without evaluating them, so unlike
get_type_hints() this does not require the annotation names to be
resolvable at class creation time.

Adds four tests in tests/test_typedattr.py covering subclassing with new
attributes, an empty subclass, and that the annotation guard still fires
both for a plain set and for the attributes a subclass declares itself.
Three of them fail without this patch.

Co-authored-by: CommandCodeBot <noreply@commandcode.ai>
Co-authored-by: CommandCodeBot <noreply@commandcode.ai>
The pull request link was written with a double backtick at the start
instead of the single backtick the RST link syntax needs, which left an
inline literal without a matching end-string. The docs build runs with
-W, so this failed the build with "Inline literal start-string without
end-string" at versionhistory.rst:46.

Co-authored-by: CommandCodeBot <noreply@commandcode.ai>
@pasmud

pasmud commented Sep 28, 2026

Copy link
Copy Markdown
Contributor Author

A note on the current CI status, since most of it is unrelated to this patch.

The first run failed the docs job because the pull request link in my changelog
entry was written with a double backtick instead of the single backtick the RST link
syntax needs. That has been fixed in c280702, and the docs job now passes.

The remaining red marks on the latest run are not caused by this patch:

  • 13 of the 14 failing jobs failed only in the Upload Coverage step with
    Error: Internal Server Error (500) from Coveralls. The Test with pytest step
    succeeded in every one of them.
  • The one job whose Test with pytest step failed is
    test (ubuntu-latest, pypy3.11-v7.3.23, [trio], false), on
    test_sockets.py::TestTCPStream::test_cancelled_send_does_not_send_the_next_one[trio-ipv6].
    That test sends an 8 MB payload and depends on wait_all_tasks_blocked() timing. It
    passes here on all 6 of its parametrizations, and the same job has flaked on master
    before. All five tests in tests/test_typedattr.py passed in that job.

@agronholm agronholm left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

It looks like this PR comes with too many tests, not all of them focusing on this particular fix. Keep only the relevant tests (1 might be enough).

@agronholm agronholm added this to the 4.16.0 milestone Oct 9, 2026
Comment thread tests/test_typedattr.py Resolved

@agronholm agronholm left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Thanks.

@agronholm
agronholm merged commit cd21b36 into agronholm:master Oct 20, 2026
20 checks passed
sergiparpal added a commit to sergiparpal/semantic-diff-weaver that referenced this pull request Nov 3, 2026
The first held-out split was measured after the 0.16.0 corrections and
its disagreements were read, so by benchmark/README.md a fresh one must
be labeled before the next correction is designed. This adds it.

run_benchmark.py propose drew six pull requests each from
encode/django-rest-framework, jd/tenacity, urllib3/urllib3,
agronholm/anyio, and pypa/packaging, chosen to reach the categories no
label named, authorization and retry/timeout, and those named least,
boundary and ordering; the pull requests themselves were never chosen
by hand, and propose's analyses beside the clones were deleted unread.
Claude Opus 5.5 labeled the 89 Python symbols they change outside the
tests, found from the Git objects with its own ast walk, before reading
the analyzer's output on them. sergiparpal reviewed every label on a
page that showed each symbol's diff and never the analyzer's findings,
kept 73, and corrected 16. Of the 44 behavior changes, 9 name
retry_timeout_change, 2 boundary_change, and 1 ordering_change; none
touched authorization, which stays unlabeled.

The new cases are the held_out split; the first held-out cases join
development, which has 60. Every new case's reviewed_by names the
reviewer, sampled_from gains the five repositories, and the annotation
says how both samples were labeled. tests/unit/test_benchmark.py counts
60 development cases. benchmark/README.md describes the splits and adds
two rules the review settled: a function is labeled with the functions
nested in it, as the analyzer reads it, and every Python file outside
the tests is labeled, benchmarks and noxfile.py included.
docs/benchmark.md says its results are the first round's and that the
new split has not been measured yet; the labels are committed before
any measurement on them. No analyzer behavior changes.

Each correction and its reason, as the reviewer gave it:

- encode/django-rest-framework#10021
  ModelSerializer.get_unique_together_constraints: adds boundary and
  validation. Besides widening the yielded tuples, the selection
  changes: more than one field in constraint.fields was required, and
  now at least one field and more than one in the union with the
  condition's fields, so a single-field constraint conditioned on
  another field is included; the cardinality limit and the constraints
  that reach validation change.
- encode/django-rest-framework#10021 get_unique_validators: adds
  boundary. A UniqueValidator is produced only when the field and the
  condition's fields together have exactly one element, an explicit
  cardinality condition deciding when the validator is generated.
- jd/tenacity#741 BaseRetrying._run_wait and AsyncRetrying._run_wait:
  add error handling and default behavior. The implicit zero wait no
  longer covers every falsy value: the constructor normalizes None and
  values equal to 0, but an empty string or list reaches here and
  raises TypeError when called, where it meant no wait.
- jd/tenacity#645 Retrying.__call__ and AsyncRetrying.__call__: add
  state transition and output contract. With enabled=False the first
  attempt's result is returned, where a policy retrying on the result
  could return a later, different one; begin() and the retry
  statistics are skipped, which changes observable state.
- urllib3/urllib3#5083 HTTPResponse._init_length: adds error handling.
  A value int() took, such as +42, now falls back to length=None, and a
  Content-Length such as "+1, 2", which raised InvalidHeader for
  differing lengths, now falls back through ValueError.
- urllib3/urllib3#5083 HTTPResponse._update_chunk_length: adds error
  handling, state transition, and side effect. Sizes such as +A or 0xA
  became a chunk size; now they are rejected, close() is called, and
  InvalidChunkLength is raised, closing the response's resources.
- urllib3/urllib3#5330 PoolManager.urlopen: adds error handling and
  dependency interaction. default is now passed to Retry.from_int and
  sleep_for_retry is called, which parses Retry-After and can raise
  InvalidHeader on a malformed value where the redirect was followed
  without parsing it. sleep_for_retry does not check
  respect_retry_after_header, so the rationale no longer implies it.
- agronholm/anyio#1447 groupby: adds ordering. The comparison of keys
  is reversed, next_key != group_key before and, after an identity
  check, group_key == next_key now, so the method called changes, which
  matters with asymmetric comparisons or observable effects.
- agronholm/anyio#1443 MemoryObjectReceiveStream and
  MemoryObjectSendStream: add output contract. The new _waiters field
  is a dataclass field without repr=False, and eq=False does not turn
  the repr off, so the generated __repr__ now includes it.
- agronholm/anyio#1424 SocketStream.receive: adds side effect and
  dependency interaction. The finally also calls
  transport.pause_reading() when the wait ends by cancellation or an
  exception, a call to the transport that affects incoming data.
- agronholm/anyio#1410 BlockingPortal._call_func: adds dependency
  interaction. future.cancelled() gives way to the
  set_running_or_notify_cancel() protocol, which reserves the future's
  state atomically or notifies the cancellation.
- pypa/packaging#1460 TimeSpecSuite.setup: adds error handling. A
  parametrized benchmark's call that raised TypeError for its argument
  count now enters the method.
- agronholm/anyio#1358 TypedAttributeSet.__init_subclass__: adds error
  handling, settled from the reviewer's case note: a subclass whose
  public attribute is annotated in a superclass no longer raises
  TypeError.

Settled and kept: jd/tenacity#696 and #679 retry keep their categories,
the analyzer reading a function with the functions nested in it, as
werkzeug#3329's run_wsgi was labeled with run_wsgi.execute.

Rationales: twelve corrected labels' rationales now say what their
categories describe; the others already did.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants