1

How do I access all global variables inside a module (I don't who they are in advance)?

For example

file m.py:

def a(s):
    exec('print '+s)

main code:

import m
x=2
m.a('x*2')
3
  • 4
    Don't use exec() for stuff like this. It's not a good tool for the job. Likewise, globals are a bad idea in general - pass variables you need to the function. Commented Nov 21, 2012 at 20:22
  • What do you want this to print? There is no x in m.py ... Commented Nov 21, 2012 at 20:23
  • The module is to execute python commands found in a textfile, I know that this gives all kind of security issues, but it is ok for my application. Currently I use execfile('m.py'), but I rather use modules. Commented Nov 22, 2012 at 6:25

3 Answers 3

1

You want to use eval() here and not exec().

But what are you actually trying to do....the usage of eval() and exec() is in general bad style and in general not needed (especially scary when it comes to security considerations).

Sign up to request clarification or add additional context in comments.

3 Comments

eval won't work here because print is a statement -- And anyway, eval doesn't have any way of knowing what x actually is unless you pass it globals and/or locals dictionaries.
@poke -- No it wouldn't. You still have a namespace access problem. Since there is no x in m.py, eval('x') in m.py will fail with a NameError.
@mgilson Sorry, I was only responding to the first part.
0

Why can't you just use (okay, if you seriously do have strings somehow, but then since it's almost all in code anyway, it just looks like you've got strings around it for some reason)

(re-written code):

file m.py:

def a(s):
    print s

main code:

import m
x=2
m.a(x * 2)

1 Comment

Actually the commands I want to execute come from a file as strings, not as arguments.
0

You can hack it by directly importing the special __main__ module. In m.py:

def print_global(name):
  import __main__
  print getattr(__main__, name)

And in the main module:

import m
x = 2
m.print_global('x')  # prints 2

While this example illustrates how to programatically work with the namespace, this is the kind of thing that should be done sparingly if at all.

1 Comment

have you tested this? How should globals in the namespace of m know what x is in the namespace of __main__?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.