On 11/9/2013 08:50, chandan kumar wrote:

> Hi ,
>
> I'm trying to understand using global variable across different modules.

Python doesn't have such a thing, unless you consider builtins.

> Here is what i have tried so far without much success.Please ignore any
> indentation issue  in the below code.
>

Which one is the script, and which one an imported module?  You have
bugs ether wayl, but different ones.  I have to assume something, so
I'll assume Test2.py is your script.

> Filename:Test1.py
>
> Debug_Value = " "
>
> import Test2

Nasty business.  Any time you have recursive imports, you can expect
trouble.  But importing the script is doubly bad.  You'll be importing a
second copy of the script, pretending it's a module, and you'll be
RUNNING it before this Test1 module.  Maybe that doesn't matter, since
the script does nothing useful.  But once you fix the other problems,
this one will be a big problem.

>
> def globalValmethod():
>     global Debug_Value 
>     Debug_Value =10
>     Test2.globalValTest()
>
> globalValmethod() -----Execute the method
>
> Filename:Test2.py
>
> import Test1
> from Test1 import *

Bad practice.  I wish the above syntax were not in the language.

>
> def globalValTest()
>     print "Golabal Value" Debug_Value 

You omitted any top-level code, so this function won't be called anyway.

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

After you fix the above, you'll still have the problem that you
apparently don't understand that these "variables" are names referring
to objects.  If you have two names bound to the same object, and you
rebind one of them (inside globalValmethod()), the other remains
bound to the original object.

After you rename your files so I can tell which one is intended as the
script, and which as the module, then clean up the other problems, and
remove one of the imports. Then if you're still confused, ask again.


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

There are no global variables inside a class.  There are class
attributes which are sort-of global, and it's legal to use the global
statement inside a method, as with any other function.


But the main question is probably, why are you so hung up on globals? 
If it's changeable, it usually should NOT be global.  Good uses for
globals are things like math.pi or command-line options.  The first is
always the same, and the second is initialized before anyone will use
it, and never changed afterwards.

incidentally, class names, module names, and top-level function names
are also global, and these are normally not changeable.


-- 
DaveA


-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to