Text of peps.python.org › pep-0767 as Styx crawled it on Nov 19, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

PEP 767 – Annotating Read-Only Attributes | peps.python.org

PEP 767 – Annotating Read-Only Attributes PEP 767 – Annotating Read-Only Attributes Author : Łukasz Modzelewski Sponsor : Carl Meyer <carl at oddbird.net> Discussions-To : Discourse thread Status : Draft Type : Standards Track Topic : Typing Created : 18-Nov-2024 Python-Version : 3.15 Post-History : 09-Oct-2024 05-Dec-2024 Table of Contents Abstract Terminology Motivation Classes Protocols Rationale Specification Usage Initialization Instance Attributes Class Attributes Protocols Subtyping Interaction with Other Type Qualifiers Backwards Compatibility Security Implications How to Teach This Rejected Ideas Clarifying Interaction of @property and Protocols Assignment Only in __init__ and Class Scope Allowing Bare ReadOnly With Initializing Value Footnotes Copyright Abstract PEP 705 introduced the typing.ReadOnly type qualifier to allow defining read-only typing.TypedDict items.

This PEP proposes using ReadOnly in annotations of class and protocol attributes , as a single concise way to mark them read-only. Akin to PEP 705 , it makes no changes to setting attributes at runtime. Correct usage of read-only attributes is intended to be enforced only by static type checkers. Terminology This PEP uses “read-only” to describe attributes which may be read, but not assigned to (except in limited cases to support initialization) or deleted.

Motivation The Python type system lacks a single concise way to mark an attribute read-only. This feature is present in other statically and gradually typed languages (such as C# or TypeScript ), and is useful for removing the ability to assign to or delete an attribute at a type checker level, as well as defining a broad interface for structural subtyping. Classes Today, there are three major ways of achieving read-only attributes, honored by type checkers: annotating the attribute with typing.Final : class Foo : number : Final [ int ] def __init__ ( self , number : int ) -> None : self . number = number class Bar : def __init__ ( self , number : int ) -> None : self . number : Final = number Supported by dataclasses (and type checkers since typing#1669 ).

Overriding number is not possible - the specification of Final imposes that the name cannot be overridden in subclasses. marking the attribute “_internal”, and exposing it via read-only @property : class Foo : _number : int def __init__ ( self , number : int ) -> None : self . _number = number @property def number ( self ) -> int : return self . _number Overriding number is possible, but limited to using @property . [1] Read-only at runtime. [2] Requires extra boilerplate.

Supported by dataclasses , but does not compose well - the synthesized __init__ and __repr__ will use _number as the parameter/attribute name. using a “freezing” mechanism, such as dataclasses.dataclass() or typing.NamedTuple : @dataclass ( frozen = True ) class Foo : number : int # implicitly read-only class Bar ( NamedTuple ): number : int # implicitly read-only Overriding number is possible in the @dataclass case.

Read-only at runtime. [2] No per-attribute control - these mechanisms apply to the whole class. Frozen dataclasses incur some runtime overhead. Most classes do not need indexing, iteration, or concatenation, inherited from NamedTuple . Protocols Suppose a Protocol member name: T defining two requirements: hasattr(obj, "name") isinstance(obj.name, T) Those requirements are satisfiable at runtime by all of the following: an object with an attribute name: T , a class with a class variable name: ClassVar[T] , an instance of the class above, an object with a @property def name(self) -> T , an object with a custom descriptor, such as functools.cached_property() .

The current typing spec allows creation of such protocol members using (abstract) properties: class HasName ( Protocol ): @property def name ( self ) -> T : ... This syntax has several drawbacks: It is somewhat verbose. It is not obvious that the quality conveyed here is the read-only character of a property. It is not composable with type qualifiers . Currently, Pyright disagrees that some of the above five objects are assignable to this structural type. [Pyright] [mypy] Rationale These problems can be resolved by an attribute-level type qualifier.

ReadOnly has been chosen for this role, as its name conveys the intent well, and the newly proposed changes complement its semantics defined in PEP 705 . A class with a read-only instance attribute can now be defined as: from typing import ReadOnly class Member : def __init__ ( self , id : int ) -> None : self . id : ReadOnly [ int ] = id …and the protocol described in Protocols is now just: from typing import Protocol , ReadOnly class HasName ( Protocol ): name : ReadOnly [ str ] A subclass of Member can redefine .id as a writable attribute or a descriptor .

It can also narrow its type. The HasName protocol has a more succinct definition, and can be implemented with writable instance/class attributes or custom descriptors. Specification Usage The typing.ReadOnly type qualifier becomes a valid annotation for attributes of nominal classes and protocols. It can be used at class-level and within __init__ to mark individual attributes read-only: class Book : id : ReadOnly [ int ] def __init__ ( self , id : int , name : str ) -> None : self . id = id self . name : ReadOnly [ str ] = name Use of bare ReadOnly (without [<type>] ) is not allowed.

Type checkers should error on any attempt to assign to or delete an attribute annotated with ReadOnly , except in contexts described under Initialization . It should also be an error to delete an attribute annotated as Final . (This is not currently specified.) Use of ReadOnly in annotations at other sites where it currently has no meaning (such as local/global variables or function parameters) is considered out of scope for this PEP, and remains forbidden.

ReadOnly does not influence the mutability of the attribute’s value. Immutable protocols and ABCs (such as those in collections.abc ) may be used in combination with ReadOnly to forbid mutation of those values at a type checker level: from collections import abc from dataclasses import dataclass from typing import Protocol , ReadOnly @dataclass class Game : name : str class HasGames [ T : abc . Collection [ Game ]]( Protocol ): games : ReadOnly [ T ] def add_games ( shelf : HasGames [ list [ Game ]]) -> None : shelf . games . append ( Game ( "Half-Life" )) # ok: list is mutable shelf . games [ - 1 ] . name = "Black Mesa" # ok: "name" is not read-only shelf . games = [] # error: "games" is read-only del shelf . games # error: "games" is read-only and cannot be deleted def read_games ( shelf : HasGames [ abc .

Sequence [ Game ]]) -> None : shelf . games . append ( ... ) # error: "Sequence" has no attribute "append" shelf . games [ 0 ] . name = "Blue Shift" # ok: "name" is not read-only shelf . games = [] # error: "games" is read-only All instance attributes of frozen dataclasses and named tuples should be implied to be read-only. Type checkers may inform that annotating such attributes with ReadOnly is redundant, but it should not be seen as an error: from dataclasses import dataclass from typing import Final , NewType , ReadOnly @dataclass ( frozen = True ) class Point : x : int # implicitly read-only y : ReadOnly [ int ] # ok, redundant uint = NewType ( "uint" , int ) @dataclass ( frozen = True ) class UnsignedPoint ( Point ): x : ReadOnly [ uint ] # ok, redundant; narrower type y : Final [ uint ] # not redundant, Final imposes extra restrictions; narrower type Initialization Assignment to a read-only attribute of a nominal class can only occur in the class declaring the attribute and its nominal subclasses, at sites described below.

There is no restriction to how many times the attribute can be assigned to. Type checkers may choose to warn on read-only attributes which could be left uninitialized after an instance is created (except in stubs , protocols or ABCs): class Patient : id

The rest of this page is on the live site.