Hi,
 
Looking for ideas on getting Abstract Base Classes to work as intended within a 
metaclass.
 
I was wondering if I could use an abc method within a metaclass to force a 
reimplementation when a class is instantiated from the metaclass.  It seems 
like I cannot do so.  I implemented the following test case:
 
import abc
class MetaExample(type):
  def __init__(cls, name, bases, ns):
    setattr(cls, 'cls_meth', cls.cls_meth)    # cls method as instance method
    setattr(cls, 'cls_abc', cls.cls_abc)        # abc cls method as instance 
method

 
  def cls_meth(cls):
    print('Class method defined stub')

 
  @abc.abstractmethod
  def cls_abc(cls):
    try:
      print('Class-Abstract method defined stub')
    except NotImplementedError, err:
      print('Must implement cls_abc.')
    except:
      print('General exception at cls_abc method.')
 
Then I create class MyKlass from the metaclass and instantiate it as myklass:
MyKlass(object): __metaclass__ = MetaExample
myklass = MyKlass()
myklass.cls_meth()   --> prints "Class method defined stub"
myklass.cls_abc()     --> prints "Class-Abstract method defined stub"
 
I was hopping for myklass.cls_abc() to print "Must implement cls_abc."
 
However, this makes sense since MyKlass implements from the metaclass the 
cls_abc method and there will never be an abstraction of this method.
 
Any ideas on how to get this done?  Any way I could define an abstract method 
within a metaclass and have it behave with abstraction when the class is 
created off the metaclass?
 
I other words, I want to force an implementation of cls_abc() method when 
MyKlass(object): __metaclass__ = MetaExample is declared, or else get 
NotImplementedError exception.
 
Thanks,
Boris Arloff
  


      
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to