Inter-module globals

Joel Hedlund joel.hedlund at gmail.com
Thu Mar 9 17:56:46 CET 2006


> Use a module and a class variables for that.

I think we could manage a little example too ;-) This one is a fictitious little game project where the user can define a custom graphics directory on the command line. 

Three files: game.py, graphics.py and common.py. 

The common.py file contains that class with class variables that jorge was talking about. Other modules import this as needed.

The contents of the files follow below.

So:
$ python game.py
/usr/local/mygame/data/gfx
$ python game.py --gfx-dir moo/cow
/usr/local/mygame/moo/cow
$ python game.py --gfx-dir /moo/cow
/moo/cow

Hope it helps!
/Joel Hedlund



main.py:
--------------------------------------------------------
#!/usr/bin/python

import sys

import graphics
from common import Settings

try:
    i = sys.argv.index('--gfx-dir')
except ValueError:
    pass
else:
    Settings.graphics_dir = sys.argv[i + 1]

print graphics.graphics_dir()
--------------------------------------------------------



common.py:
--------------------------------------------------------
class Settings(object):
    game_dir = '/usr/local/mygame'
    graphics_dir = 'data/gfx'
--------------------------------------------------------



graphics.py:
--------------------------------------------------------
import os

from common import Settings

def graphics_dir():
    return os.path.join(Settings.game_dir, Settings.graphics_dir)
--------------------------------------------------------



    



Jorge Godoy wrote:
> Anton81 <forum at anton.e4ward.com> writes:
> 
> 
>>I want to use globals that are immediately visible in all modules. My
>>attempts to use "global" haven't worked. Suggestions?
> 
> 
> Use a module and a class variables for that.  Import your module and
> read/update class variables as you need them.
> 
> 



More information about the Python-list mailing list