I'm trying to validate and format a class variable. The class extends a class with ABCMeta
as its __metaclass__
and I can't yet instantiate my child class. So when I run this below code it prints property object and not
the output I want, which I understand why. But then how do I do it?
from abc import ABCMeta, abstractproperty
class RuleBase(object):
__metaclass__ = ABCMeta
id = None
id = abstractproperty(id)
@property
def format_id(self):
try:
_id = 'R%02d' % self.id
except TypeError:
raise TypeError("ID must be an integer")
return _id
@classmethod
def verbose(cls):
print cls.format_id
class Rule(RuleBase):
id = 1
Rule.verbose() # prints property object and not R01
In my theory, I think this would work.
class FormattingABCMeta(ABCMeta):
def __new__(mcl, classname, bases, dictionary):
# Format here, remove format_id property from RuleBase,
# and use FormattingABCMeta as metaclass for RuleBase.
return super(C, mcl).__new__(mcl, classname, bases, dictionary)
But then I feel I'm twisting it too much. So, how to do this? And is my understanding correct? Any help is appreciated.