Confused about hasattr/getattr/namespaces

Bob Ippolito bob at redivi.com
Sun Feb 29 14:07:38 EST 2004


On 2004-02-29 13:48:21 -0500, brian at mirror.org (Brian Roberts) said:

> I'm confused about the use of hasattr/getattr, or possibly
> namespaces.  I know how to do this:
> 
> class UnderstandThis(object):
>     def do_foo(self): pass
>     def do_bar(self): pass
>     def doit(self, cmd):
>         funcname = 'do_' + cmd
>         if hasattr(self, funcname):
>             getattr(self, funcname)()
>         else:
>             print 'not found'
> 
> But if I try to do this with classes in a module (instead of
> functions in a class):
> 
> class FooGenerator(object): ...
> class BarGenerator(object): ...
> 
> def generate(cmd):
>     clsname = cmd + 'Generator'
>     if hasattr(???, clsname):
>         etc...
> 
> I don't know what to use for ??? instead of self.  If I print
> globals() inside generate() it shows the two classes, but using
> it in the hasattr line doesn't work -- huh?  I can make it work
> by wrapping the generate function in a (otherwise useless) class
> and using self -- again, huh?
> 
> Couldn't find an explanation or example in the docs.  In fact,
> the description of vars/globals/locals (in section 2.1) just
> confused me even more.  Think I'm heading down the wrong path.
> Can somebody please un-confuse me?

if you have the module object, you can use that.. or you could use 
sys.modules[__name__] to get the current module (import sys, of course).

globals(), locals() are dictionaries, so you would have to do "clsobj = 
globals().get(clsname)" or something like that.  You *probably* want 
something more explicit than that though.. it probably wouldn't be too 
much work to keep your own command->class dictionary.

-bob




More information about the Python-list mailing list