Am 19.08.21 um 16:11 schrieb Sebastian Rittau:
This was previously briefly discussed in https://github.com/python/typing/issues/601.
Occasionally it's useful if it was possible to mark protocol fields as optional. While the existence of such a field is not guaranteed, if it exists, it follows the described protocol. This is especially useful for I/O protocols, where implementations often check for the existence of a particular method, before using it. One prominent example is the WSGI spec, where the iterable returned by an application can optionally have a close() method.
My suggestion is to add an @optional decorator to typing to be used like this:
from typing import Protocol, optional
class MyProto(Protocol): def write(self, __b: bytes) -> Any: ... @optional def close(self) -> Any: ...
On the Python side, this is fairly trivial to implement: @optional would just return the passed in function, possible adding an attribute for runtime inspection:
def optional(f: _F) -> _F: f.__optional__ = True return f
Full support for type checkers is more complicated, as hasattr() support would be required to check implementations. A quick & dirty way for type checkers to support the status quo is to ignore @optional fields.
It would also be possible to add support for non-method fields by re-using PEP 655's NotRequired type. This mean that @not_required might be a more consistent name for the decorator: class MyProto: x: NotRequired[int] @not_required def foo(self) -> None: ... - Sebastian