global variable not seen (bug?)
Michal Vitecek
fuf at mageo.cz
Wed Jan 8 12:56:15 EST 2003
Peter Hansen wrote:
>"Globals" are not really *global* in Python, they are visible only
>throughout the module in which they are defined, not throughout the
>entire application.
>
>You've defined "GLOBAL_VARIABLE" in the module used for the interactive
>interpreter (well, I think that's roughly what happens... it's close
>enough for this discussion) but someFunction() is defined in another
>module which has its _own_ "namespace" (basically, the set of names
>that it recognizes). Even though you've imported a name from the
>"imported" namespace into your own namespace(*), you don't change
>the fact that someFunction() looks in the namespace of the "imported"
>module to find the "global".
>
>(*) The form "from module import *" is, by the way, generally a bad
>idea, but you can read the archives to find out why as it has
>been much discussed in the past.
>
>-Peter
Peter, thank you for your response.
i must say that this behaviour of "global" variables is IHMO pretty
uncommon and non-intuitive and i wonder what was the reason the
developers chose this way:
1) either that global variables have module-only scope
2) method even though it is imported into different scope still
looks for data in module in which it was defined
what i wanted was an easy solution to be able to access (read/write,
etc.) data files in my python scripts. the data files are located in
some fixed directory but the scripts (with classes that operate on
them) can be whatever deep in directories and be imported and used from
scripts that can be again whatever deep. some example:
projectRootDirectory:
importFileModuleToWorkOnFile.py*
projectRootDirectory/dataFiles:
File.dat
projectRootDirectory/classes:
FileModuleWorkingOnFile.py
projectRootDirectory/tests:
testFileModuleWorkingOnFile.py*
where * denotes executable python script and module
FileModuleWorkingOnFile.py contains a class that wants to be able to
access file File.dat no matter what is the location of executable
script importing it. if real globals were supported in python i could
have the scripts roughly as follows:
importFileModuleToWorkOnFile.py:
PROJECT_ROOT_DIRECTORY = "."
# sys.path tweaking
import FileModuleWorkingOnFile
# make an instance of class ClassWorkingOnFile() and call its
# methods to do some work on file File.dat
...
testFileModuleWorkingOnFile.py:
PROJECT_ROOT_DIRECTORY = ".."
# sys.path tweaking
import FileModuleWorkingOnFile
# make an instance of class ClassWorkingOnFile() and call its
# methods to do some work on file File.dat
...
FileModuleWorkingOnFile.py:
class ClassWorkingOnFile(object):
...
def workOnFile(self):
global PROJECT_ROOT_DIRECTORY
f = open(PROJECT_ROOT_DIRECTORY + "/dataFiles/File.dat")
...
is there any feasible way to achieve this?
thank you for your help,
--
fuf (fuf at mageo.cz)
More information about the Python-list
mailing list