Pure virtual functions in Python?

Martin v. Loewis martin at v.loewis.de
Sat Feb 20 18:08:33 CET 2010


>> class C1:
>>
>>      # Pure virtual
>>      def cb(self, param1, param2):
>>          """
>>          This is a callback
>>
>>          @param param1: ...
>>          @param param2: ...
>>          """
>>          raise NotImplementedError, "Implement me"
>>
>> # Dispatcher function that calls 'cb' only if 'cb' is implemented in
>> child classes
>> def dispatcher(c):
>>      if hasattr(c, 'cb'):
>>          c.cb("Hello", "World")
>>
>> dispatcher(C2())
>> dispatcher(C3())
>>
>> What I want is the ability to have the dispatcher() not to call 'cb'
>> if it was not implemented in one of the child classes.
>>
>> Please advise.
> 
> There is nothing more beyond that what you already did. You can raise a
> NotImplementedError for classes that don't implement the method. That's it.

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



More information about the Python-list mailing list