emihir0
emihir0

Reputation: 1250

Creating a dynamic class that inherit class it is made in

When I try to create a class from within a parent class, such that the child class inherits 'self', I get the following error:

TypeError: Error when calling the metaclass bases metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

class A(object):
    create_proxy = False

    def __init__(self, *args, **kwargs):
        super(A, self).__init__(*args, **kwargs)
        if self.create_proxy:    
            class Proxy(SomeMixin, self):
                pass

            [...]

I'm sure this is somehow possible; any suggestions?

Upvotes: 1

Views: 53

Answers (1)

Abhijith Asokan
Abhijith Asokan

Reputation: 1875

Make the following change

...
if self.create_proxy:    
    class Proxy(SomeMixin, A): #use class name instead of self
        pass
...

Also make sure that SomeMixin is a subclass of object, otherwise it will result it metaclass conflict.

class SomeMixin(object):
    pass


class A(object):
    create_proxy = True #False
    def __init__(self, *args, **kwargs):
        super(A, self).__init__(*args, **kwargs)
        if self.create_proxy:    
            class Proxy(SomeMixin, A):
                pass

a = A() #test

Upvotes: 2

Related Questions