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:
I like the idea but not the name, since this will mean something very different from `typing.Optional`. I'd suggest `@not_required`, matching the proposed new NotRequired mechanism for TypedDicts, which has similar semantics.
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.
More precisely, type checkers could ignore `@optional` fields when checking for compatibility, but still allow calls to such methods on protocol-typed values.
- Sebastian
_______________________________________________
Typing-sig mailing list -- typing-sig@python.org
To unsubscribe send an email to typing-sig-leave@python.org
https://mail.python.org/mailman3/lists/typing-sig.python.org/
Member address: jelle.zijlstra@gmail.com