Pure virtual functions in Python?

Martin v. Loewis martin at v.loewis.de
Sun Feb 21 04:24:24 EST 2010


>> That's not true. Currently, the hasattr() call would report that cb is
>> available, when it is actually not implemented. It would be possible to
>> do something like
>>
>>   if hasattr(c, 'cb') and not is_pure(c.cb):
>>       c.cb("Hello", "World")
>>
>> is_pure could, for example, look at a function attribute of the
>> callback. You'd write something like
>>
>>   @pure_virtual
>>   def cb(self, param1, param2):
>>       not_implemented
>>
>> Regards,
>> Martin
> 
> Hello Martine,
> 
> Can you elaborate more on how to use the mechanism you described?

There are various ways to do it; the one I had in mind uses function
attributes:

def pure_virtual(func):
  func.pure_virtual = True # only presence of attribute matters,
                           # not value
  return func

def is_pure(method): # method might be either a method or a function
  try:
    func = method.im_func
  except AttributeError:
    func = method
  return hasattr(func, 'pure_virtual')

not_implemented = object() # could also write pass instead, or raise

HTH,
Martin



More information about the Python-list mailing list