Last active
May 27, 2022 00:22
-
-
Save henriquebastos/81287351109e841e64c47c0cfa5baced to your computer and use it in GitHub Desktop.
Example of using abc.ABC to enforce implementation of abstractmethods.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pytest | |
from abc import ABC, abstractmethod | |
class Animal(ABC): | |
@abstractmethod | |
def emit_sound(self): | |
pass | |
@abstractmethod | |
def eat(self): | |
pass | |
def concrete_method(self): | |
return 42 | |
def test_require_impl_of_abstractmethods(): | |
class Dog(Animal): | |
pass | |
Dog() # Will raise TypeError! | |
def test_dont_require_impl_of_concretemethods(): | |
class Dog(Animal): | |
def eat(self): | |
print('cookie') | |
def emit_sound(self): | |
print('bark') | |
dog = Dog() | |
assert isinstance(dog, Animal) | |
assert dog.concrete_method() == 42 | |
if __name__ == "__main__": | |
pytest.main(["-s", __file__]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment