Here's a few ideas:

Solution 1 - use the __main__ module

The downside to this is that it always reads x from the "top-level"
module, in other words, the script that is being run.  So when you run
a1, you'll get "a1" when you run a2 module b will then find "a2".

a1.py
------------------
import b
x = "a1"
b.test()
------------------

a2.py
------------------
import b
x = "a2"
b.test()
------------------


b.py
------------------
import __main__
def test():
        print __main__.x
------------------

I'm not sure why you're trying to do this, but it looks like having b
reference variable x which is implied to have been defined elsewhere
could cause trouble for you later.  x is sort of like a parameter to
make b work differently, so you should probably explicitly pass it to
functions in b or use x to initialize an object of a class from b.

Idea 2 - use a class to encapsulate x

If you wrap up all the functionality you need in a class inside b, you
could then pass x to the constructor and all the subsequent method
calls would have access to x.

a1.py
------------------
import b
x = "a1"
my_b = b.B(x)
my_b.test()
------------------

a2.py
------------------
import b
x = "a2"
my_b = b.B(x)
my_b.test()
------------------

b.py
------------------
class B(object):
        def __init__(self, x):
                self.x = x
        def test(self):
                print self.x
------------------

Solution 3 - Use the borg pattern

If you need all modules everywhere to see b with the same value of x,
you could use the borg pattern (singleton would work too, but I like
borg better).  This way the first a module that gets imported or run
will set b's value of x forever.

a1.py
------------------
import b
x = "a1"
my_b = b.B(x)
my_b.test()
------------------

a2.py
------------------
import b
x = "a2"
my_b = b.B(x)
my_b.test()
------------------

a3.py - note that this one will print "a1" twice, since module a1
initializes b before a3 can.
------------------
import a1
import b
x = "a3"
my_b = b.B(x)
my_b.test()
------------------

b.py
------------------
class B(object):
        borg = None
        def __init__(self, x):
                if B.borg is None:
                        B.borg = {}
                        B.borg['x'] = x
                self.__dict__ = B.borg

        def test(self):
                print self.x
------------------




--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to