I have a program that compares two classes in a series of tests.
The main program (called initial.py) assigns both values to a dictionary
import testcheck
values = {}
valueChange = False
if __name__ == "__main__":
values['valueOne'] = testcheck.assignValue() #see note 1
values['valueTwo'] = testcheck.assignValueTwo()
testcheck.checkValues() #see note 2
while valueChange is True :
values['valueTwo'] = testcheck.assignValueTwo()
testcheck.checkValues()
Note 1: both of these return the same class but with different values
Note 2: compares the two classes. after a series of tests, valueChange is set to True, and one value is to be deleted using this code
import initial
...
if initial.valueChange is True:
del initial.values['valueTwo']
...
This returns the error
del initial.values['valueTwo']
KeyError: 'valueTwo'
I thought it was because adding valueOne and valueTwo would be adding it in the local scope, but even with global values it doesn’t fix it. How would I go about solving this?
This appears to be a design issue. You seem to be setting up circular imports, which should be avoided if possible. If what you are after is to share a global state across modules of your package, you might want to make use of storing the state within your
testcheckmodule, and not in a global variable of yourinitial.pytestcheck.py
initial.py
otherModule.py
I have no idea where this whole thing is going in terms of real usage. But maybe this will give you an idea of where to start looking. There is no longer a circular import of other modules importing your intial.py entry point. You are storing all the globals within the testcheck module. This example is very quick and dirty. Its only to illustrate.
No module should ever try to be accessing data of another module which handles the data within an
if __name__ == "__main__"block. Because now you are making the assumption that it will always be used as the entry point (never imported by something else) and you start putting restrictions on your code.