1

Using something from on another page on this site, I've managed to create global variables that are accessible across modules by doing something along the lines of--

Mod1.py--

def init():
    global testVar

mod2.py--

import mod1
mod1.init()
print(mod1.testVar)

How, though, in mod2.py, can I dynamically access global variables in mod1? Something like--

nameOfVarThatIWant = 'testVar'
print(mod1.globals()[nameOfVarThatIWant])
martineau
  • 119,623
  • 25
  • 170
  • 301
JTron
  • 23
  • 3
  • 1
    It would just be `import mod;print(mod.varname)`. `global varname` doesn't do anything; if it's not defined elsewhere, you want to make an assignment to the variable. – sytech Mar 05 '18 at 19:11
  • Yes, but I want varname to be a dynamic string – JTron Mar 05 '18 at 19:12
  • OK, but global or not global, how do I access it from another module dynamically just by specifying a string that's the name of the variable? – JTron Mar 05 '18 at 19:16
  • Not sure what you mean by *dynamic string*. You just access the variables like `mod.varname` that's it. Is there something incomplete there? Instead, can you describe *why* you're trying to do this? In general, you don't want your application to rely on global state... you especially don't want that global state to be mutated if it can be avoided. See [this question](https://stackoverflow.com/questions/19158339/why-are-global-variables-evil) for details on why relying on global state can be bad for your application. – sytech Mar 05 '18 at 19:16
  • Reading your comment again, perhaps what you're looking for is `getattr`... `getattr(mod, 'some_name')` would return the same thing as `mod.some_name`. Is that what you're trying to get at? – sytech Mar 05 '18 at 19:18
  • Add a function to mod1 that when called with a string argument uses mapping the built-in `globals()` function returns the access the corresponding variable's value. – martineau Mar 05 '18 at 19:19
  • OK, just forget about it being global. If it's just mod1: a = 5 then in another module, it would be import mod1; print(mod1.a) . How could I do something like test = 'a'; mod1.test to access mod1.a ? – JTron Mar 05 '18 at 19:21
  • getattr() and built-in globals() would both work I think. Thank you!!! – JTron Mar 05 '18 at 19:24

1 Answers1

0

Answer based on the two very helpful comments above--

getattr(mod1, nameOfVarThatIWant)

or built-in function in mod1 that uses globals()

JTron
  • 23
  • 3