setattr inside a module

Jeremy Bowers jerf at jerf.org
Wed Mar 23 12:56:21 EST 2005


On Wed, 23 Mar 2005 11:35:34 +0100, kramb64 wrote:

> I'm trying to use setattr inside a module.
> From outside a module it's easy:
> 
> import spam
> name="hello"
> value=1
> setattr(spam, name, value)
> 
> But if I want to do this inside the module spam itself, what I've to
> pass to setattr as first argument?
> 
> Thanks a lot for your time.
> Marco.

As others point out, 

sys.modules[__name__]

I find myself doing this more and more, not less, as I get further into
Python; autogenerating many similar functions, pulling constants from an
external source, stuff like that, usually very meta and every instinct
says its the right thing to do. 

Maybe we should have a __module__ attribute that is a reference to the
current module? sys.modules[__name__] is a little obtuse.




More information about the Python-list mailing list