1

how do you inherit globals from other .py file?

Example:
globals.py

test = 'testValue'

index.py

from globals import *

def setGlobals():
    global test
    test = 'new Value' # Setting new value to project global  

setGlobals()

help.py

from globals import *
print test # Should print out 'new Value', but it prints 'testValue'

I wish to have one file full of constants and global variables that is set by another file and also used by other files. In this example I set new value to global variable test in index.py and wish to use new value in help.py. Am I using the wrong approach for python? Thank you.

EDIT: Sequence of events is same as exampled, e.g. first I import, set new value and then try printing out newly set value from another file.

4

2 回答 2

1

In Python modules are objects. When you do an import, you are copying and possibly renaming the attributes of one module into the current module. However, this only copies the value (or more specifically copies the reference by value). If the imported module is later changed, your copy won't be. One possible approach is to try defining your globals in the second module as properties, but I'm not sure if that even works.

However, what you are trying to do is terrible design anyway. You need to rethink why you want to have global values being accessed and modified everywhere. Try refactoring your code and replacing anything left with dependency injection. For example, replace your globals module with a configuration object that you can pass around to whoever needs it.

于 2012-08-30T11:45:54.017 回答
0

According to:

Inside index.py you would remove:

global test

Then you would change:

test = 'new Value' # Setting new value to project global

To:

globals.test = 'new Value' # Setting new value to project global

In help.py you would change:

print test # Should print out 'new Value', but it prints 'testValue'

To:

print globals.test # Should print out 'new Value', but it prints 'testValue'

I'm actually working on a similar project tonight so will comeback and confirm website's correctness later (although it makes sense it is correct).

It seems confirmed by this link:

As an aside I'm somewhat surprised stack overflow doesn't have an answer on this yet other than the too often occurring accepted answer of "You can't do that". I don't have c++ experience like you do in comments. But I have used c and psuedo c# and having header files you include for global variables seems like a no-brainer and not something to be shunned. I do it in Linux bash all the time with source config.sh, etc.

于 2020-09-11T00:02:11.003 回答