开发者

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

开发者 https://www.devze.com 2023-01-12 00:01 出处:网络
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:

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(), l开发者_StackOverflow社区etter, 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).


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'])
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号