Skip to content

Instantly share code, notes, and snippets.

@timhughes
Created March 19, 2021 22:17
Show Gist options
  • Save timhughes/44aab228fed6e6e2775b10f0ca3ed565 to your computer and use it in GitHub Desktop.
Save timhughes/44aab228fed6e6e2775b10f0ca3ed565 to your computer and use it in GitHub Desktop.
multiple clas inheritance of ABCs with asyncio
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())
@timhughes
Copy link
Author

  File "/home/thughes/git/gitlab-radiator/scratch/abcinherit.py", line 51, in <module>
    asyncio.run(main())
  File "/usr/lib64/python3.9/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/usr/lib64/python3.9/asyncio/base_events.py", line 642, in run_until_complete
    return future.result()
  File "/home/thughes/git/gitlab-radiator/scratch/abcinherit.py", line 44, in main
    foo = MyClass(verify=False)
  File "/home/thughes/git/gitlab-radiator/scratch/abcinherit.py", line 19, in __new__
    return super(MyABC, cls).__new__(cls, *arg, **kwargs)
TypeError: object.__new__() takes exactly one argument (the type to instantiate)```

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment