TypedDict-exclusive typing for Protocol

In typing.TypedDict, there are three exclusive types: typing.Required, typing.NotRequired and typing.ReadOnly, while we can’t mark any attributes as NotRequired in typing.Protocol, which is possible in TypeScript.

I think it might be a good idea letting user use Required, NotRequired and ReadOnly in typing.Protocol. This is especially useful for typing some old libraries, like win32com.server.register from pywin32.

My Vision

class Register(Protocol):
	_reg_clsid_: PyIID
	_reg_progid_: NotRequired[str]

class cls1:
	_reg_clsid_ = IID('...')
var1: type[Register] = cls1 # OK

class cls2:
	_reg_clsid_ = IID('...')
	_reg_progid_ = '...'
var2: type[Register] = cls2 # OK

class cls3:
	_reg_clsid_ = IID('...')
	_reg_progid_ = 0
var3: type[Register] = cls3 # Error

I have good news for you, at least as far as ReadOnly is concerned there already is a PEP: PEP 767: Annotating Read-Only Attributes

Expanding Required/NotRequired to protocols has also already come up a few times, but nobody went as far as writing a PEP for that yet and there seems to be overall less of an appetite for it.

That being said, I do agree that it makes perfect sense to expand those qualifiers to work in Protocol, since both TypedDict and Protocol are structural types. Someone just has to be willing to put in the required work to advance the proposal beyond just an ideas thread.

1 Like

For reference, there is an open issue about this: Optional class and protocol fields and methods · Issue #601 · python/typing · GitHub This would be especially useful for I/O protocols that often call methods like close conditionally.

1 Like