What is more Pythonic: subclass or adding functionality to base class?

Paul Moore p.f.moore at gmail.com
Sun Feb 11 08:41:36 EST 2018


On 11 February 2018 at 12:55, D'Arcy Cain <darcy at vybenetworks.com> wrote:
> On 02/11/18 06:30, Victor Porton wrote:
>> What is more pythonic?
>>
>> 1. Create its subclass PredicateParserWithError and add the additional field
>> on_error to this class.
>>
>> 2. Add on_error field to the base class, setting it to None by default, if
>> the class's user does not need this field.
>
> Personally I would go with #1.  It just seems cleaner.  Not sure what
> the Python gods would do.

I don't know about "Python Gods" or even what's more Pythonic, but it
might be worth commenting that if this were Java, adding a new field
to the base class would need every file that used the class to be
recompiled. So there's a tendency to subclass just to minimise the
impact of a change like this. In Python, that's not necessary, as
classes are created at runtime, and there's no compile-time layout
that code needs to depend on, so if you add an extra field to a class,
only those parts of your codebase that need the new field have to
care.

Of course, if this is a public API, backward compatibility and
versioning of the API become issues, that may affect your decision.
Paul



More information about the Python-list mailing list