Bialecki
Bialecki

Reputation: 31051

How do I dynamically add an attribute to a module from within that module?

Say in a module I want to define:

a = 'a'
b = 'b'
...
z = 'z'

For some set (in this case I chose letters). How do I dynamically set attributes on the current module? Something like:

for letter in ['a', ..., 'z']:
    setattr(globals(), letter, letter)

This doesn't work, but what would? (Also my understanding is that globals() within a module points to a dict of the attributes of that module, but feel free to correct me if that's wrong).

Upvotes: 3

Views: 1062

Answers (1)

Dave Kirby
Dave Kirby

Reputation: 26552

globals() returns the dictionary of the current module, so you add items to it as you would to any other dictionary. Try:

for letter in ['a', ..., 'z']:
    globals()[letter] = letter

or to eliminate the repeated call to globals():

global_dict = globals()
for letter in ['a', ..., 'z']:
    global_dict[letter] = letter

or even:

globals().update((l,l) for l in ['a', ...,'z'])

Upvotes: 10

Related Questions