Skip to content

Commit 3ae2ce5

Browse files
committed
Specially mention super().__new__()
Clarify that inheriting from a protocol makes it behave like a nominal class (wrt ReadOnly)
1 parent c24a6a5 commit 3ae2ce5

File tree

1 file changed

+14
-5
lines changed

1 file changed

+14
-5
lines changed

peps/pep-0767.rst

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -281,9 +281,12 @@ Assignment to a read-only instance attribute must be allowed in the following co
281281

282282
* In ``__init__``, on the instance of the declaring class received as
283283
the first parameter (usually ``self``).
284-
* In ``__new__`` and ``@classmethod``\ s, on instances of the declaring class
285-
created via a call to ``__new__`` on any object of type ``type[T]``, where
286-
``T`` is a *nominal supertype* of the declaring class.
284+
* In ``__new__`` and ``@classmethod``\ s, on instances of the declaring class created via:
285+
286+
- a call to ``super().__new__()``,
287+
- a call to ``__new__`` on any object of type ``type[T]``,
288+
where ``T`` is a *nominal supertype* of the declaring class.
289+
287290
* At declaration in the class scope.
288291

289292
Additionally, a type checker may choose to allow the assignment
@@ -421,6 +424,12 @@ is assignable to ``T``:
421424
422425
Read-only protocol attributes may not be assigned to or deleted in any context.
423426

427+
Note that when inheriting from a protocol to `explicitly declare its implementation <https://typing.python.org/en/latest/spec/protocol.html#explicitly-declaring-implementation>`__,
428+
for the purpose of applying rules regarding read-only attributes (that the protocol may define),
429+
the protocol should be treated as if it was a nominal class.
430+
In particular, this means that subclasses *can* initialize read-only attributes
431+
that have been defined by the protocol.
432+
424433
Type checkers should not assume that access to a protocol's read-only attributes
425434
is supported by the protocol's type (``type[HasName]``). Even if an attribute
426435
exists on the protocol's type, no assumptions should be made about its type.
@@ -436,8 +445,8 @@ Subtyping
436445
The inability to assign to or delete read-only attributes makes them covariant.
437446
This has a few subtyping implications. Borrowing from :pep:`705#inheritance`:
438447

439-
* Read-only attributes can be redeclared as writable attributes, descriptors
440-
or class variables::
448+
* Read-only attributes can be redeclared by a subclass as writable attributes,
449+
descriptors or class variables::
441450

442451
@dataclass
443452
class HasTitle:

0 commit comments

Comments
 (0)