[Python-ideas] abc.optionalabstractmethod

Eric Snow ericsnowcurrently at gmail.com
Thu Aug 2 17:26:59 CEST 2012


Sometimes you want to specific an optional method in an abstract base
class.  Currently we don't have a consistent way of doing so, instead
having to mix in the old way of defining "abstract" methods:

class MyABC(metaclass=ABCMeta):
    ...

    def do_something_optional(self):
        """An optional method for doing something."""
        raise NotImplementedError

This came up in issue 15502[1], where we are splitting
importlib.abc.Finder into MetaPathFinder and PathEntryFinder.  These
have a method, invalidate_caches(), which is optional.  It would be
nice to have a new decorator akin to abstractmethod that would allow
defining an optional interface in a consistent way.  Something like
optionalabstractmethod (or some better name).  Then the above example
would be like this:

class MyABC(metaclass=ABCMeta):
    ...

    @optionalabstractmethod
    def do_something_optional(self):
        """An optional method for doing something."""

Thoughts?

-eric


[1] http://bugs.python.org/issue15502; Barry Warsaw voiced what I've
considered on multiple occasions.



More information about the Python-ideas mailing list