global variable not seen (bug?)

Carl Banks imbosol at vt.edu
Wed Jan 8 14:29:04 EST 2003


Michal Vitecek wrote:
> 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
>    ...


Many consider it bad style to do file processing (and other
complicated stuff) while importing a module.  In general, I highly
recommend against it.  If "File.dat" is a configuration or data file
that is only to be read once, then it might make sense to do it that
way, but I would still put the file processing in a function and call
it after importing the module.  That's what I suggest: it would then
be easy to pass the location of the file as an argument to the
function.

If you insist on doing this while importing, then don't bother with
globals.  The location of the file should be a member of the
ClassWorkingOnFile object.  You can pass the location as part of the
constructor, when you make it's instance:

    ClassWorkingOnFile(....whatever....,file_location='.')

      - or -

    ClassWorkingOnFile(....whatever....,file_location='..')


-- 
CARL BANKS




More information about the Python-list mailing list