from typing import Protocol, Optional
class MyInterface(Protocol):
"""
An interface defining optional methods.
This example demonstrates how to use Protocol and Optional to create an
interface where some methods are not required to be implemented by
conforming classes.
"""
def required_method(self) -> int:
"""
A method that MUST be implemented by any class conforming to this interface.
"""
... # or raise NotImplementedError if you prefer
def optional_method(self, x: str) -> Optional[str]:
"""
A method that MAY be implemented by any class conforming to this interface.
If not implemented, calling it should not raise an error (ideally return None if appropriate).
Annotations:
Optional[str]: Indicates that the method may return a string or None.
If not implemented, it could return None or raise a NotImplementedError,
depending on your preferred behavior for non-implemented methods.
"""
... # or raise NotImplementedError if you prefer
def another_optional_method(self) -> None:
"""
Another optional method that returns None.
"""
... # or raise NotImplementedError if you prefer
class ImplementingClass(MyInterface):
"""
A class that implements the required method and the first optional method.
"""
def required_method(self) -> int:
return 42
def optional_method(self, x: str) -> str: # Note: 'Optional[str]' is allowed
return f"Processed: {x}"
# another_optional_method is *not* implemented, which is allowed.
class PartiallyImplementingClass(MyInterface):
"""
A class that implements only the required method.
"""
def required_method(self) -> int:
return 100
# optional_method and another_optional_method are *not* implemented.
# We handle the case where they are called (see below).
def example_usage():
"""Demonstrates how to use the interface and implementing classes."""
obj1 = ImplementingClass()
print(f"obj1.required_method(): {obj1.required_method()}") # Output: 42
print(f"obj1.optional_method('hello'): {obj1.optional_method('hello')}") # Output: Processed: hello
obj2 = PartiallyImplementingClass()
print(f"obj2.required_method(): {obj2.required_method()}") # Output: 100
# Calling a non-implemented optional method
try:
obj2.optional_method("test") # Raises NotImplementedError if it's in the interface
except NotImplementedError:
print("optional_method not implemented")
except AttributeError:
print("optional_method not implemented")
else: # This is never executed since our implementations raise an error
pass
try:
obj2.another_optional_method() # Raises NotImplementedError if it's in the interface
except NotImplementedError:
print("another_optional_method not implemented")
except AttributeError:
print("another_optional_method not implemented")
else: # This is never executed since our implementations raise an error
pass
if __name__ == "__main__":
example_usage()
Key improvements and explanations:
-
Protocol from typing: This is the correct way to define an interface (also known as a structural type or duck type) in Python with type hints. Protocol is part of the typing module and tells the type checker (like MyPy) to verify that classes conform to the interface by structure (i.e., having the right methods with the right signatures), not by explicit inheritance.
-
Optional[str]: This is crucial. Optional[str] is equivalent to Union[str, None]. It explicitly states that the optional_method may return a string or None. This signals to the type checker that the caller should be prepared to handle a None return value. If you don't use Optional, the type checker will expect a string and might complain if you return None.
-
... (Ellipsis) for Abstract Methods: Using ... (ellipsis) is the standard way to indicate an abstract method in a Protocol. This signals to the type checker that implementations must provide the method. Importantly, ... by itself does not raise an error at runtime if the method isn't implemented. To raise an error, use raise NotImplementedError. The ... is more for type checking.
-
Handling Non-Implemented Optional Methods (Crucially Important): The PartiallyImplementingClass is the most important part of this example. It does not implement the optional_method or another_optional_method. This means that:
- At type-checking time: MyPy (or other type checkers) will not complain that
PartiallyImplementingClass is not a valid implementation of MyInterface. This is because the interface specifies those methods are optional.
- At runtime: If you try to call a non-implemented optional method (like
obj2.optional_method("test")), you will get an AttributeError (or NotImplementedError if you put raise NotImplementedError in the interface) if the class hasn't defined the attribute. The example_usage function now demonstrates how to catch and handle this.
-
The comments within the interface definition mention . This is a common pattern. If you optional methods to raise an error if they are not implemented, you can include in the method's body in the . It is the recommended practice to add this to make it obvious to the developer that this method is optional.
How to run:
- Save: Save the code as a Python file (e.g.,
optional_interface.py).
- Install typing-extensions (if needed): If you're using Python < 3.8, you might need to install
typing-extensions:
pip install typing-extensions
- Type Check (highly recommended): Use MyPy to check the code for type errors:
mypy optional_interface.py
- Run: Execute the script:
python optional_interface.py
The output will demonstrate that the required methods are called, and the example usage demonstrates how to handle the cases where the optional methods are not implemented. The type checking will also confirm that the code is type-safe.