Trying to get ABC to work

Roman r.a.teterin at gmail.com
Tue Aug 4 19:08:45 CEST 2009


Following code works, although I'm not sure that it's exactly what you
want:

   import abc
   
   class MetaExample(abc.ABCMeta):
       def __new__(mcs, name, bases, ns):
           ns['cls_meth'] = mcs.cls_meth
           if not 'cls_abc' in ns:
               ns['cls_abc'] = mcs.cls_abc
           return super().__new__(mcs, name, bases, ns)
   
       def cls_meth(cls):
           print('Class method defined stub')
   
       @abc.abstractmethod
       def cls_abc(cls):
           try:
               print('Class-Abstract method defined stub')
           except NotImplementedError as err:
               print('Must implement cls_abc')
           except:
               print('General exception at cls_abc method')

That's how I've tested it:

   class Test1(object, metaclass=MetaExample):
       def cls_abc(self):
           print("method of", self)
   
   class Test2(object, metaclass=MetaExample): pass
   
   test1 = Test1()
   test1.cls_meth()
   test1.cls_abc()
   
   test2 = Test2()

Output:
   Class method defined stub
   method of <__main__.Test1 object at 0xb7b5f52c>
   Traceback (most recent call last):
     File "/tmp/test.py", line 32, in <module>
       test2 = Test2()
   TypeError: Can't instantiate abstract class Test2 with abstract methods cls_abc

According to the documentation, @abstractmethod "requires that the
metaclass is ABCMeta or derived from it", so I've changed base class
from type to ABCMeta. Also I don't think that using try/except inside the
abstract method will work, maybe it would be better to check presence of
all required methods directly inside the metaclass, without
@abstractmethod decorator.



More information about the Python-list mailing list