[Python-ideas] abc.optionalabstractmethod

Eric Snow ericsnowcurrently at gmail.com
Fri Aug 3 05:19:14 CEST 2012


On Thu, Aug 2, 2012 at 9:37 AM, Simon Sapin <simon.sapin at kozea.fr> wrote:
> Le 02/08/2012 17:26, Eric Snow a écrit :
>
>> 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
>
>
> Hi,
>
> What’s wrong with this?
>
> I think that the only thing making methods with @abstractmethod special is
> that they prevent instantiation if they are not overridden. If we remove
> that, the only remaining difference is terms of documentation. Maybe a new
> Sphinx directive could help?
>
> What would an optional abstract method do when it is called? Raise
> NotImplementedError?
>
> I’m not against this idea but I just don’t see how @optionalabstractmethod
> is better than raise NotImplementedError

Yeah, there isn't a huge win (particularly considering the
implementation would tread on perilous ground*).  The main motivation
is consistency in the definition of abstract base classes.  How would
it work?  Yeah, probably a lot like the NotImplementedError technique
works.  Or perhaps it would simply be removed by the ABCMeta when the
class is built.

-eric


* If you have an hour or two to spare, manually trace trough the abc
module and Objects/typeobject.c to see how abstract base classes work
under the hood.  Totally worth it!



More information about the Python-ideas mailing list