Creating variables from dicts

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Wed Feb 24 15:44:41 CET 2010


Luis M. González a écrit :
> On Feb 24, 8:48 am, Bruno Desthuilliers <bruno.
> 42.desthuilli... at websiteburo.invalid> wrote:
>> Luis M. Gonz lez a crit :

>>
>>> And what about the trick of updating globals? Is it legal?
>> It's legal, but it's (usually) a very bad idea - at the top-level, it
>> harms readability, and from within a function it's doubly bad
>> (readibility + "globals are evil").
>>
>> Now as usual with GoldenRules(tm), it's meant to be broken - once you do
>> know why you shouldn't _usually_ do it.
>>
>>> If not, is
>>> there any "legal" way to do what the OP needs?
> 
> I still don't understand why is it a bad idea in the case of
> globals().

please not the _usually_.

> This is the only way I know to define variables programatically  in the
> top-level namespace,  without having to do it manually one by one.

> I don't see the readability problem either.

# wrong.py

x = 42

def bar():
    return x + 1


def test():
    y = bar()
    assert y==43

# snip 1kloc

def foo():
    globals()[x] = 43
    quux()

# snip some more core

def quux():
    globals()[y] = 1138

# snip some more core

if __name__ == '__main__':
    foo()


Enjoy...

> Talking about Goldenrules(tm), what's the recomended way to do it?

The "recommanded way" is
1/ to avoid using globals to share state whenever possible
2/ to avoid creating globals from a function

If your problem is to conditionnaly define globals (based on environment 
value or whatnot), then just write the conditional at the top level.

Now I don't say there's no legitimate use case for updating the global 
namespace from within a function - just that this is a very very very 
rare beast (never meet her as far as I'm concerned, and I did write some 
hairy code), and even then is BadEnough(tm) to require a good documentation.

FWIW, your example seemed to be about updating the global namespace from 
within a function just to have the names available in the function, 
which is about the worst possible solution to the OP problem.

wrt/ the OP question, mapping a sequence of values to a sequence of 
names is a legitimate concern, but you just dont need to define these 
names in the local namespace to use them - just stick'em in a dict and 
you're fine.




More information about the Python-list mailing list