Inter-module globals

A

Anton81

Hi,

I want to use globals that are immediately visible in all modules. My
attempts to use "global" haven't worked. Suggestions?

Anton
 
J

Jorge Godoy

Anton81 said:
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.


--
Jorge Godoy <[email protected]>

"Quidquid latine dictum sit, altum sonatur."
- Qualquer coisa dita em latim soa profundo.
- Anything said in Latin sounds smart.
 
?

=?ISO-8859-1?Q?Sch=FCle_Daniel?=

Anton81 said:
Hi,

I want to use globals that are immediately visible in all modules. My
attempts to use "global" haven't worked. Suggestions?

Anton

I think a dictionary would work here
as well as list but not strings and int's

# module1
settings = {
"release" : "1.0",
"blabla" : None,
}

# module2
import module1 as settings
print settings.settings["release"]
settings.settings["blabla"] = True


# module3
import module1 as settings
settings.settings["blabla"] = False

Regards
 
J

Joel Hedlund

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,289
Messages
2,571,435
Members
48,121
Latest member
ColinHibne

Latest Threads

Top