How to dynamically add a module attribute from this module?

Say in the module I want to define:

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

For some set (in this case, I chose the letters). How to dynamically set attributes in the current module? Sort of:

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

It does not work, but what will happen? (I also understand that globals () inside a module points to an attribute of that module, but feel free to fix me if it's wrong).

+3
source share
1 answer

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

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

or to eliminate the repeated call of global variables ():

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

or even:

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

Source: https://habr.com/ru/post/1759557/


All Articles