1

I have two files random1.py, random2.py

random2.py has

def your():  
    global mine  
    mine = 10

random1.py has

import random2.py

global mine
mine = 4
random.your()
print mine

random1.py prints out 4 not 10.

My ultimate goal is to have functions that can take in any possible variable that has been declared and have the new values for that variable available after the function is run. I have all of the functions in a separate file though for organization. I noticed it works if I have them in the same file.

I am trying to replicate the functionality of procedures from Hoc

wcarvalho
  • 33
  • 3
  • This code won't print `4`; it'll die with an `ImportError`. Anyway, this is a bad idea, and Python will not make it easy for you to do it. You're much better off using arguments to pass data into functions and return values to pass data out. – user2357112 Aug 02 '13 at 21:26
  • Keyword `global` has a misleading name because it accesses the variable of the namespace of the module (=script file) it is in – Michael Butscher Aug 02 '13 at 21:29

1 Answers1

0
Could you please directly use **random2.mine** instead of declaring it global again, which makes separate copy of mine variable in random1's namespace.

random2.mine = 50
print(random2.mine)


# Another way of modifying attributes of imported module is 
random2.__dict__[mine] = 100
print(random2.mine)

http://docs.python.org/2/tutorial/classes.html#python-scopes-and-namespaces
http://stackoverflow.com/questions/6841853/python-accessing-module-scope-vars
Pavan Gupta
  • 17,663
  • 4
  • 22
  • 29