Adding to a module's __dict__?

Chris Rebert clp2 at
Tue Mar 2 06:38:34 CET 2010

On Mon, Mar 1, 2010 at 8:27 PM, Roy Smith <roy at> wrote:
> >From inside a module, I want to add a key-value pair to the module's
> __dict__.  I know I can just do:
> FOO = 'bar'
> at the module top-level, but I've got 'FOO' as a string and what I
> really need to do is
> __dict__['Foo'] = 'bar'
> When I do that, I get "NameError: name '__dict__' is not defined".  Is
> it possible to do what I'm trying to do?

Yes; just modify the dict returned by the globals() built-in function
instead. It's usually not wise to do this and is better to use a
separate dict instead, but I'll assume you know what you're doing and
have good reasons to disregard the standard advice due to your

One should avoid using the Big Hammer unnecessarily,
but sometimes you really do need it and it's nice that it's available
for such cases.

More information about the Python-list mailing list