what's the best way to call a method of object without a guarantee of its existence
Marco Mariani
marco at sferacarta.com
Tue May 5 06:25:08 EDT 2009
Leon wrote:
> One way, define the object before it is used,
> like this:
> object = None
This is a good practice anyway. Conditional existance of objects is
quite evil. Resorting to if defined('foo') is double-plus-ugly.
> The other way, using try ... catch
> try:
> object.method()
> catch NameError:
> pass
Except you should trap AttributeError because you defined the thing as
None before. NameErrors should be fixed as bugs, not trapped (IMHO --
but in python there is always a use case for everything).
Keep in mind that AttributeError might come from inside the method(),
which could be confusing
By using the
if stuff:
stuff.run()
idiom, you avoid the last issue and keep it simple enough.
> for big programs, which is better, or any other way?
Define "big", as in scope, LOCs, or number of committers?
More information about the Python-list
mailing list