Implicit initialization is EXCELLENT

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Jul 5 11:26:06 EDT 2011


This is not strictly Python, although it is peripherally relevant.

Some month or three ago, I read an article or blog post about API design,
specifically the wrong-headedness of insisting that callers manually
initialise instances using a separate step after creation.

The argument goes, if your API looks something like this:

instance = Spaminator(extra_truffles=False)
instance.activate()
instance.nom_nom_nom()
=> prints "yummy spam, the food of the Gods!!!"

chances are that you are doing it wrong and your users will hate you. Why
force the user to manually "flip the switch" (so to speak)? It's not like
they can possibly avoid it:

another_instance = Spaminator(with_extra_cheese=True)
another_instance.nom_nom_nom()
=> raises InactiveInstanceError("you must activate the instance first")

What? No! Just activate yourself!

Exceptions to this rule are if the Spaminator has side-effects (e.g. files,
in which case the user may want finer control in when they are opened and
closed), or if there are meaningful operations you can perform on an
inactive Spaminator.

Python generally follows this design. Apart from files, I can't easily think
off the top of my head of any types that require a separate
open/start/activate call before they are usable. It's also relevant to
tkinter, which will implicitly create a root window for you when needed.
Since you can't do anything without a root window, I don't see the benefit
in forcing the user to do so. When they need to learn about root windows,
they will in their own good time.

Now, I have an ulterior motive in raising this issue... I can't find the
original article I read! My google-fu has failed me (again...). I don't
suppose anyone can recognise it and can point me at it?
 


-- 
Steven




More information about the Python-list mailing list