I am trying to learn metaclasses in python, from my research i found a example like follow.
i have a Base and Derived classes like follow
class Base():
def foo(self):
return self.bar()
class Derived(Base):
def foo2(self):
return "i am foo2"
now, when i want to make sure that whoever extending Base class, must need to implement bar() method, so i created the meta class to hook the constuction of derived class,so now Base class looks like follow with BaseMeta meta class.
class BaseMeta(type):
def __new__(cls, name, bases, body):
if not "bar" in body:
raise TypeError("bar not implemented")
return super().__new__(cls, name, bases, body)
class Base(metaclass=BaseMeta):
def foo(self):
return self.bar()
The problem is when i get looks into body it returns 2 records for Base and Derived class, like follow.
{'__module__': '__main__', '__qualname__': 'Base', 'foo': <function
Base.foo at 0x7ffbaae436a8>}
{'__module__': '__main__', '__qualname__': 'Derived', 'bar': <function
Derived.bar at 0x7ffbaae437b8>}
my code in __new__ breaks since Base not have bar, but i want to check only in the Derived class so i rewrite my metaclass like follow.
def __new__(cls, name, bases, body):
if name !="Base" and not "bar" in body:
raise TypeError("bar not implemented")
return super().__new__(cls, name, bases, body)
I am checking name != Base in my __new__ method.
Is that the right way to do it or we can use some other best way?
metaclassto achieve this right?__init_subclass__to verify assertions about a child without defining a metaclass.