NB question on global/local variables in functions
skip at pobox.com
skip at pobox.com
Sat Jul 15 07:53:05 EDT 2006
Wolfgang> So I have some variables which should be accessible by all my
Wolfgang> functions but not accessible by the rest of my code. How can I
Wolfgang> do this?
Wolfgang> ###function.py:
Wolfgang> c1=123.0
Wolfgang> c2=134.0
Wolfgang> def fun(temp):
Wolfgang> return temp+c1-c2
Wolfgang> def fun1(temp):
Wolfgang> return temp-c1
Wolfgang> ### caller.py
Wolfgang> from function import *
Wolfgang> print fun(10.0)
Wolfgang> print c1
First, avoid "from function import *" as it pollutes your namespace. Either
import specific symbols or just the module:
from function import fun, fun1
import function
Second, if you really must, add an __all__ list to function.py, generally
right at the top:
__all__ = ['fun', 'fun1']
(Note that __all__ is a list of strings.) The "from star" import will only
import the names in the __all__ list. You can also "hide" individual names
from a "from star" import by prefixing them with a single underscore (e.g.,
"_c1" instead of "c1").
Third, one of Python's key concepts is "we're all adults here". You can't
really and truly hide c1 and c2, so just act responsibly and don't mess with
them from outside the function module.
Skip
More information about the Python-list
mailing list