-5

I have a small question: If I run this:

print(list(globals()))

this is the output:

['__package__', '__loader__', '__doc__', , '__file__', 'b', '__name__', '__builtins__', 'a']

I want to try a method with all of these elements, especially a and b.

But this would be like:

'a'.run()

so this doesn´t work at all.

I need something like:

a.run()
mehdi lotfi
  • 11,194
  • 18
  • 82
  • 128
vossmalte
  • 174
  • 2
  • 2
  • 16

3 Answers3

2

Use the string as the key to the dictionary returned by globals. The resulting value will be the actual object. Example:

a = "hello world!"
print globals()["a"].split()

Here, the method split is called on the variable a. Result:

['hello', 'world!']
Kevin
  • 74,910
  • 12
  • 133
  • 166
  • sorry, thats not what i want. my problem is this: b=any_class() now calling globals() into a list, and me wanting to run b isn't possible, because if i do, it tries this: "b".run() – vossmalte Sep 18 '13 at 17:42
  • @m00lti That's not really a problem. What is the actual problem you are trying to solve? – Marcin Sep 18 '13 at 17:49
  • @m00lti Yes, so to run something on `b`, you need a reference to the actual object, not a string of the name. That is what Kevin gives you a method of doing in this answer. Please re-read the answer, understand it and try to apply it before writing it off. – Gareth Latty Sep 18 '13 at 17:55
1

If you already know that the object is called a, just access the variable directly: a.run().

If you don't know the variable name, then you surely don't know if it refers to a value with a run method, so it's far from safe to attempt to call it in that way.

Whatever you're trying to do, there is almost certainly a better way.

Marcin
  • 48,559
  • 18
  • 128
  • 201
0

in this particular case, you're bumping into the way iteration over dict's work. When you do list(some_dict), you get a list of the keys of some_dict. It happens that globals() is a dict, and so you get the keys of that dict, the 'names' of the global things. You can get the values from a dict in the obvious way: list(some_dict.values()), and you can even get both key and value together with some_dict.items().

So your example could be

for something in globals().items():
    something.run()

More generally, if you had some arbitrary list of names you need to resolve, you probably don't want to use this sort of approach.

SingleNegationElimination
  • 151,563
  • 33
  • 264
  • 304