what's the best way to call a method of object without a guarantee of its existence

Leon QJing.Li at gmail.com
Tue May 5 17:42:15 EDT 2009

On May 5, 3:25 am, Marco Mariani <ma... at sferacarta.com> wrote:
> 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.

This was why I asked this question. In my program, I use the pattern
object.method() a lot, but every time I need to check if it exists or
which makes me feel uncomfortable.

> > 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?
"big", I mean, is not in the same scope
For instance,

class frame(wx.Frame):
  def __init__(self, parent, ....):
      self.parent = parent # parent from another module

  def eventHandler_1(self,event):
      if self.parent.object_1 is not None:

  def eventHandler_2(self, event):
      if self.parent.object_2 is not None:

So I need to go back to the module including "parent" class
to define the objects that I maybe use in future as None,
actually, the module including "parent' class works very well
without those definitions, from parent class's point of view,
those definitions are kind of noisy.

Thanks Marco

More information about the Python-list mailing list