0

I need to instantiate some keys of a Dict as a standalone global variables.

(Before you object let me mention that this is purely for testing purposes and i know it pollutes the global scope. It is not intended as programing technique.)

OK. Now that out of the way. If I use simple function like the one below it works.

def items_as_vars(obj, lst) :
    for i in lst :
        globals()[i] = obj.g(i)
        print i, obj.g(i)

items_as_vars(obj, ['circle','square'])

print circle

but the moment I move this to become class method in a separate file it stops working i.e.

class blah:
    @staticmethod
    def items_as_vars(obj, lst) :
       for i in lst :
            globals()[i] = obj.g(i)
            print i, obj.g(i)

blah.items_as_vars(obj, ['circle','square'])

print circle

NameError: name 'circle' is not defined

any idea why ? By "stop working", I mean the global variables are no longer instantiated.


More info: It seems to work when the class is in the same file, but not when the class is imported !


modified to static method, it is the same behaviour.

sten
  • 7,028
  • 9
  • 41
  • 63

1 Answers1

1

You need to use __builtin__ to create cross-module variables. Like this:

class SomeClass(object):
    def g(self, x):
        return x
    def items_as_vars(self, lst) :
        for i in lst :
            import __builtin__
            setattr(__builtin__, str(i), self.g(i))
            print i, self.g(i)

In [9]: import test

In [10]: test.SomeClass().items_as_vars(['x', 'yz'])
x x
yz yz

In [11]: yz
Out[11]: 'yz'
Cory Madden
  • 5,026
  • 24
  • 37