[Tutor] variables question.

Steven D'Aprano steve at pearwood.info
Fri Nov 12 03:24:23 CET 2010

Jeff Honey wrote:
> I have a question about where variables are exposed in python.
> I have a monolothic script with a number of functions defined, can those functions share variables? can I instantiate them outside the function of where they are needed? do they need to be wrapped in quotes, ever?

It sounds to me that you've come to Python from bash or shell scripting.

Python has no real equivalent to the idea of quoting variable names, and 
there's never any need to quote variables to protect them from being 
accidentally evaluated. There's no risk in doing this:

x = 1
s = "del x"

and having the variable x accidentally deleted because you neglected to 
quote the variable s correctly. Nor is there any simple way you can do 

a = "something"
b = "a"
print($b)  # prints "something"

although there is eval and exec, both of which are dangerous/advanced 
and should be avoided unless you really know what you're doing.

Aside: the idiomatic way of doing that in Python would be:

data = {"a": "something"}
key = "a"
print(data[key])  # prints "something"

> ...what about my python being called from some parent script (something OTHER than python) that instantiates blah and foo FOR me? 

If you want to gather information from external sources, you need to 
choose a way to have that information fed into your script. The easiest 
way is to use command-line arguments. Python has lots of different ways 
to get to command-line arguments -- see the getopt and optparse modules 
in the standard library, and the argparse third-party module, and 
probably others.

Another way is with environment variables. Python can read env variables 
set by the calling process using os.getenv.


More information about the Tutor mailing list