object.enable() anti-pattern

Chris Angelico rosuav at gmail.com
Thu May 9 23:08:03 EDT 2013


On Fri, May 10, 2013 at 12:30 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> I must admit I am astonished at how controversial the opinion "if your
> object is useless until you call 'start', you should automatically call
> 'start' when the object is created" has turned out to be.

I share your astonishment. This is a very simple point: If, after
constructing an object, the caller MUST call some method on it prior
to the object being of use, then better design is to embed that call
directly into the constructor. As always, it has its exceptions, but
that doesn't stop it being a useful rule.

The Path() equivalent would be:

p = Path()
p.set_path("/foo/bar")
if p.exists():
  pass

Even if you have a set_path() method, it makes good sense to symlink
it to __init__ to avoid this anti-pattern.

C level APIs often have these sorts of initialization requirements.

fd_set selectme;
FD_ZERO(&selectme);

This is because declaring a variable in C cannot initialize it.
Anything that *has* constructors should be using them to set objects
up... that's what they're for.

Where's the controversy?

ChrisA



More information about the Python-list mailing list