Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Lazy superclass evaluation

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading