Python Circular Dependencies, Unable To Link Variable To Other File
Solution 1:
The import
mechanism is designed to allow circular imports. But one must remember the following:
The name of the main module created from the startup script is
__main__
, rather than as its filename minus.py
. Any other file importing the startup script mustimport __main__
, notimport filename
. (Otherwise, a second module based on the startup script will be created with its normal name.)Execution of the code in a module is paused at each
import
. The order of initial imports is important as the last module in the chain is the first to be run to completion. Each object within modules must be available when the reference is executed. References within function definitions are not executed during the import process.
Applying the above to your pair, I assume that gui.py
is the startup script. Python will immediate create an empty module object as the value of sys.modules['__main__']. So
main.pyshould import
gui.pywith
import main as gui(the name change is just for convenience). Within the function definition, you should be able to use
gui.entrywithout problem since there will be no attempt to lookup
gui.entryuntil the function is called. I suggest adding
entry = gui.entryas the first line of the function and using
entry` in the two places needed.
The following pair of files run as desired when tem2.py is run.
# tem2.pyimport tem3
a = 3print(tem3.f())
# tem3.pyimport __main__ as tem2
deff():
return tem2.a
Solution 2:
Move the definition of entry
into a third file and import it in both files.
Solution 3:
You can pass the entry to WebsiteChange
:
def WebsiteChange(entry):
website = entry.get()
submit = Button(master, text="Submit",
command=lambda e=entry: main.WebsiteChange(e))
Post a Comment for "Python Circular Dependencies, Unable To Link Variable To Other File"