Python nowadays supports "protocols". Protocols are mostly a typing thing, and allow you to specify that a class follows the protocol without explicitly being a subclass.
When using the BMI as an abstract base class, you currently need to use the following syntax:
defupdate_bmi(bmi: BmiABC) ->None:
bmi.update()
classBmiImplementation(BmiABC):
defupdate(self) ->None:
....
update_bmi(BmiImplementation()) # happy type checker
If you don't subclass BMI, type checkers will get angry at this, as BmiImplementation is not a subclass of BmiABC:
defupdate_bmi(bmi: BmiABC) ->None:
bmi.update()
classBmiImplementation:
defupdate(self) ->None:
....
update_bmi(BmiImplementation()) # sad type checker
However, if you specify that Bmi is a subclass of typing.protocol, the following syntax passes type checkers:
defupdate_bmi(bmi: BmiProtocol) ->None:
bmi.update()
classBmiImplementation:
defupdate(self) ->None:
...
update_bmi(BmiImplementation()) # happy type checker
This is because type checkers will check if BmiImplementation follows the BmiProtocol: does it have all methods that are in the protocol, and do all the methods have the correct typing.
To implement this, all that we would need to change is;
fromtypingimportProtocolclassBmi(Protocol):
Note that you can still subclass from Protocol like you could from an ABC.
Python nowadays supports "protocols". Protocols are mostly a typing thing, and allow you to specify that a class follows the protocol without explicitly being a subclass.
When using the BMI as an abstract base class, you currently need to use the following syntax:
If you don't subclass BMI, type checkers will get angry at this, as
BmiImplementationis not a subclass ofBmiABC:However, if you specify that
Bmiis a subclass oftyping.protocol, the following syntax passes type checkers:This is because type checkers will check if
BmiImplementationfollows theBmiProtocol: does it have all methods that are in the protocol, and do all the methods have the correct typing.To implement this, all that we would need to change is;
Note that you can still subclass from Protocol like you could from an ABC.