global variable not seen (bug?)

Christopher A. Craig com-nospam at ccraig.org
Wed Jan 8 16:46:09 EST 2003


Michal Vitecek <fuf at mageo.cz> writes:

>  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:


Four ways to do this come to mind.  I prefer the first two, but the
others might sit better with you.

1) Have an option to the function for the directory, and pass it from 
   the program (good if you only have one function that needs it in
   the directory)

def foo(dir, otherargs):
   ...

2) Make the module into an object and have its __init__ function set
   an instance variable with the directory (if everything in the
   module modifies the directory)

class DOSTUFFTODIR:
  def __init__(self, dir):
    self.dir = dir
  ...

3) Have an accessor function that sets the variable in the
   module-global scope and call it immediately after importing the
   module.

def setdir(dir):
  global DIR
  DIR=dir

4) directly modify the module-global variable from the calling scope.

import ModuleWithGlobal

ModuleWithGlobal.GLOBALVAR = "."

-- 
Christopher A. Craig <com-nospam at ccraig.org>
"I believe in God, and if I woke up in hell
I'd still believe in him" Robert Louis Stevenson





More information about the Python-list mailing list