Global variables not able to transfer values python

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I am new to python and trying to use Global variables were I can transfer values between two files test1.py and test2.py through an intermediate file global_var.py . I was able to put together these from what I read in few stackoverflow questions and demos. But I am not sure if am doing it write cuz its not working. Please tell me where am going wrong

global_var.py

    key_gen = []
    def init():
         global key_gen

test1.py

    import global_var
    global_var.init()
    global_var.key_gen = [1,2,3]

test2.py

    import global_var
    k = global_var.key_gen
    print k

However, the print doesn t give [1,2,3]. It instead gives [ ]. Can you please tell me how can I get this right? Thanks in advance

Edit : If I remove this statement

    key_gen = []

from global_var.py and run the same code again, I do not get any error while executing test1.py but when I run test2.py I get the following error

   Traceback (most recent call last):
   File "test2.py", line 3, in <module>
   k = global_var.key_gen
   AttributeError:  module  object has no attribute  key_gen 

I am not able to completely understand why this is happening.

Answers

You misunderstood something about the lifetime of module globals. Altering state in the Python interpreter is not persisted to disk. Changing global_var.key_gen from a script does not result in that change being saved when the interpreter exits again.

https://docs.python.org/2/library/shelve.html https://docs.python.org/2/library/shelve.html

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/23829022/global-variables-not-able-to-transfer-values-python

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils