Created
March 19, 2021 22:17
-
-
Save timhughes/44aab228fed6e6e2775b10f0ca3ed565 to your computer and use it in GitHub Desktop.
multiple clas inheritance of ABCs with asyncio
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
from abc import ABC, abstractmethod | |
import asyncio | |
import inspect | |
class MyABC(ABC): | |
def __new__(cls, *arg, **kwargs): | |
# get all coros of A | |
parent_coros = inspect.getmembers(MyABC, predicate=inspect.iscoroutinefunction) | |
# check if parent's coros are still coros in a child | |
for coro in parent_coros: | |
child_method = getattr(cls, coro[0]) | |
if not inspect.iscoroutinefunction(child_method): | |
raise RuntimeError( | |
"The method %s must be a coroutine" % (child_method,) | |
) | |
return super(MyABC, cls).__new__(cls, *arg, **kwargs) | |
@abstractmethod | |
async def print(self): | |
pass | |
class SomeClass: | |
def __init__(self, verify: bool = True): | |
self.verify = verify | |
async def hello(self): | |
print("Hello World") | |
class MyClass(MyABC, SomeClass): | |
def __init__(self, *arg, **kwargs): | |
super().__init__(*arg, **kwargs) | |
async def print(self): | |
await asyncio.sleep(0) | |
print("Hello ABC") | |
async def main(): | |
foo = MyClass(verify=False) | |
#foo = MyClass() | |
await foo.print() | |
await foo.hello() | |
print(foo.verify) | |
asyncio.run(main()) |
Author
timhughes
commented
Mar 19, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment