Style: global configuration data

Boudewijn Rempt boud at rempt.xs4all.nl
Mon Nov 13 10:03:22 EST 2000


Michael Hudson <mwh21 at cam.ac.uk> wrote:

<...>

> In the conceptual model I have of Python, there's no way anything else
> could happen ... what were you expecting?

More or less that they would be decoupled - I must have misunderstood
the warning in Internet Programming with Python (p. 173 - ... does not
create a shared variable between the modules ...). But I see that they
talk about what you say below:


> PS:  You dont want to do
> from config import setting
> setting = 2
> ... because it won't work.

Curiously enough, in the more complicated example below 'from config
import Config' does work... Probably a silly oversight on my part,
but I can't see the real difference:

--------- config.py ----------
class Config:

  foo=10

--------- classa.py ----------
from config import Config

class classA:

  def __init__(self):
    Config.foo="A"

  def p(self):
    return Config.foo
--------- classb.py ----------
from config import Config

class classB:

  def __init__(self):
    Config.foo="B"

  def p(self):
    return Config.foo
--------- classc.py ----------
class classC:

  def __init__(self):
    self.__foo="self.__foo == classC"
    
  def getFoo(self):
    return self.__foo
   
  def setFoo(self, foo):
    self.__foo=foo
  
  def __repr__(self):
    return str("Class C=='" + self.__foo +"'")
--------- app.py   -----------
ifrom config import Config
from classa import *
from classb import *
from classc import *

print "1. app: ", Config.foo

a=classA()
print "2. app: ", Config.foo, ", a: ",a.p()

b=classB()
print "3. app: ", Config.foo, ", b: ", b.p(), ", a:", a.p()

Config.foo="app"
print "4. app: ", Config.foo, ", a: ", a.p(), ", b: ", b.p()

Config.foo=classC()
print "5. app:", Config.foo, ", a:", a.p(), ", b:", b.p()

Config.foo.setFoo("app2")

print "6. app:", Config.foo, ", a:", a.p(), ", b:", b.p()

print "7:", Config.foo.getFoo()
----------------------------
Output:

boud at calcifer:~/src/python/prj/kura/test/config > python app.py
1. app:  10
2. app:  A , a:  A
3. app:  B , b:  B , a: B
4. app:  app , a:  app , b:  app
5. app: Class C=='self.__foo == classC' , a: Class C=='self.__foo == classC' , b: Class
C=='self.__foo == classC'
6. app: Class C=='app2' , a: Class C=='app2' , b: Class C=='app2'
7: app2 

Anyway, thanks for your help!

-- 

Boudewijn Rempt  | http://www.valdyas.org



More information about the Python-list mailing list