Checking for attribute in the current module with getattr( )

Alex Martelli aleax at aleax.it
Wed Aug 8 05:24:55 EDT 2001


"Just van Rossum" <just at letterror.com> wrote in message
news:3B70451D.7AC520DF at letterror.com...
> Lyle Johnson wrote:
>
> > > Now, as indicated I don't really know what object to send in to the
> > > hasattr function, indicated with "???" - is what I'm trying to do
> > > possible, and how should I in case do it?
> >
> > How about:
> >
> >     if globals().has_key("func1"):
> >         print "This module defines func1"
> >     else:
> >         print "This one doesn't"
>
> Or
>
>     try:
>         func1
>     except NameError:
>         print "This one doesn't define func1"
>     else:
>         print "This module defines func1"

That's slightly wider than the original poster had asked for
(and Lyle provided), although it may of course be what the
original poster *wanted* (i.e., it's possible that the o.p.
didn't express himself entirely clearly).  Just's version
says "this module defines func1" even if func1 was really
installed into __builtins__ by some OTHER module, for ex...


Alex






More information about the Python-list mailing list