Can module access global from __main__?
Steve Holden
steve at holdenweb.com
Tue Oct 11 10:11:32 EDT 2005
Neal Becker wrote:
> Suppose I have a main program, e.g., A.py. In A.py we have:
>
> X = 2
> import B
>
> Now B is a module B.py. In B, how can we access the value of X?
>
>
Without trying in any way to dodge the question, why do you want to do that?
There's a property of software called "coupling" that's used to describe
the way that communications take place between different components of a
piece of software. Ideally modules should be loosely-coupled, which is
usually achieved by passing values in as function or method arguments
and receiving the results as the return values of said functions or methods.
When a module is loosely-coupled in this way it's possible to revise the
structure of one component completely (while maintaining the same
interface specification) without affecting any other component.
By introducing some magic "load a variable from the namespace of the
importing module" you make your modules tightly-coupled, which is very
bad for maintainability: what happens if you now import B.py into a
module that doesn't create an X in its namespace?
The fact that you ask the question implies that you really need to think
a little harder about the structure of your program. If you tell us the
*real* problem (back to my "why do you want to do that" question ...)
perhaps we can suggest a better-structured solution.
regards
Steve
PS: If A is the main program (the module that you have run) then you
should be able to access it as __main__.X, but you'd be *very naughty*
to do so :-)
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/
More information about the Python-list
mailing list