python - Is enforcing an abstract method implementation unpythonic? -


when designing classes abstract methods can helpful. know, python not have mechanism enforcing inherited class implement abstract method. in code (see example below) enter failed assertion in base class cause runtime error if not implemented. unpythonic?

class dog(animal):   def speak(self):    return "bark"  class animal():   def speak(self):    assert(false) #abstract 

python does have abstract classes abstact methods:

>>> import abc >>>  >>> class ifoo(object): ...     __metaclass__ = abc.abcmeta ...      ...     @abc.abstractmethod ...     def foo(self): ...         pass ...  >>> foo = ifoo() traceback (most recent call last):   file "<stdin>", line 1, in <module> typeerror: cant instantiate abstract class ifoo abstract methods foo >>> class fooderived(ifoo): ...     pass ...  >>> foo = fooderived() traceback (most recent call last):   file "<stdin>", line 1, in <module> typeerror: cant instantiate abstract class fooderived abstract methods foo >>> class fooimplements(fooderived): ...     def foo(self): ...         print "foo'ed" ...  >>> foo = fooimplements() >>> foo.foo() foo'ed >>>  

on other hand, fundamental question of "is pythonic" bit harder say. if intent provide abstract base class can later check make sure values inherit it, no, that's not particularly pythonic, though it's possible make arbitrary types abstract subclasses of baseclass. on other hand, it's fine provide abstract baseclass implements functionality based upon implementation provided in concrete subclasses. example, collections.sequence , collections.mapping list , dict classes; subclasses can provide __getitem__ , can __contains__ , others free.

for certain, should never use assert() except document expectations of code; if it's possible assert fail, shouldn't using assert. optimized python (python -o script.py) not check assertions.

edit: more exposition:

if checking type of value:

def foo(bar):     if not isinstance(bar, abstractbaz):         raise valueerror, ("bar must instance of abstractbaz, "                            "got %s" % type(bar)) 

if reason can't use @abstractmethod, still want effect, should raise notimplementederror. might want because want instances of class, of might not need implement optional functionality. still should account possibility function called through super(). first approximation, might this.

class foo(object):     def bar(self, baz):         if self.bar.im_func == foo.bar.im_func:             raise notimplementederror, "subclasses must implement bar" 

Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

go - golang pprof for c library code -