I need to define a class MyClass within a developed package. The class MyClass should inherit from another class, from an external library ext_lib.Class. So the situation I want to achieve is:
class MyClass(ext_lib.Class):
def __init__(self):
super().__init__()
However, there is a trick to be done here. I want my package to work without ext_lib. It should be required iff a user wants to create a MyClass instance
I tried to use meta class:
class MetaClass(type):
def __new__(cls, name, bases, attrs):
import ext_lib
bases += (ext_lib.Class,)
new_cls = super().__new__(cls, name, bases, attrs)
return new_cls
class MyClass(metaclass=MetaClass):
def __init__(self):
...
However, I still have an error that the ext_lib is not installed before initialization.
Do you have any hint how to achieve the desired goal?
>Solution :
The __new__ method of a metaclass is called when a class object using the metaclass is created when the class statement is executed, so the import statement is effectively executed unconditionally with this approach.
A workaround is to use a function that dynamically creates the class only when called:
def MyClass(*args, **kwargs):
import ext_lib
class _MyClass(ext_lib.Class):
def __init__(self, *args, **kwargs):
pass
return _MyClass(*args, **kwargs)