Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #53964

Re: global variable across modules

References <1378903830.83908.YahooMailBasic@web190503.mail.sg3.yahoo.com>
Date 2013-09-11 23:15 +1000
Subject Re: global variable across modules
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.251.1378905331.5461.python-list@python.org> (permalink)

Show all headers | View raw


On Wed, Sep 11, 2013 at 10:50 PM, chandan kumar <chandan_psr@yahoo.co.in> wrote:
> In Test2.py file I wanted to print the global value ,Debug_Value as 10.I'm not getting expected result.Please can any one point where exactly i'm doing wrong.
>
> Similarly , how can i use global variable  inside a class and use the same value of global variable in different class?Is that possible?if Yes please give me some pointers on implementing.

Python simply doesn't have that kind of global. What you have is
module-level "variables" [1] which you can then import. But importing
is just another form of assignment:

# Test1.py
Debug_Value = " "

# Test2.py
from Test1 import *
# is exactly equivalent to
Debug_Value = " "

It simply sets that in Test2's namespace. There's no linkage across.
(By the way, I strongly recommend NOT having the circular import that
you have here. It'll make a mess of you sooner or later; you actually,
due to the way Python loads things, have two copies of one of your
modules in memory.) When you then reassign to Debug_Value inside
Test1, you disconnect it from its previous value and connect it to a
new one, and the assignment in the other module isn't affected.

Here's a much simpler approach:

# library.py
foo = 0

def bar():
    global foo
    foo += 1


# application.py
import library

library.bar()
print(library.foo)


This has a simple linear invocation sequence: you invoke the
application from the command line, and it calls on its library. No
confusion, no mess; and you can reference the library's globals by
qualified name. Everything's clear and everything works.

ChrisA

[1] They're not really variables, they're name bindings. But close
enough for this discussion.

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: global variable across modules Chris Angelico <rosuav@gmail.com> - 2013-09-11 23:15 +1000

csiph-web