PEP 767: Annotating Read-Only Attributes

Something like this is desperately needed in the type system, but I would suggest a few changes:

A read-only attribute name: T on a Protocol in principle defines two requirements:

  1. hasattr(obj, "name")
  2. isinstance(obj.name, T)

I wouldn’t call such a thing ReadOnly, but Readable. A read-only member of a protocol needs to satisfy an additional axiom: (3) setattr(obj, name, T) raises an Exception. I believe this is a simple oversight in this section, but at the end of the day, both concepts are necessary in order to facilitate correctly annotating duck-typed code: Need a way to type-hint attributes that is compatible with duck-typing - #19 by randolf-scholz

So if it is possible, it would be very nice to get Type Qualifiers Readable, ReadOnly, Writeable and WriteOnly and Mutable all in one go.

2 Likes