How do I put all of my active modules in the same 'namespace' in python?

50 views Asked by At

My '/' directory looks like this.

Launch.py
Services.py
Server.py
ServerHelper.py
Packetlib.py

When Launch is run, Launch imports Services and Server, which imports Services and Serverhelper, Which import Services, Services, Server, and PacketLib, which imports Services.

See the issue?

This is not only a terrible way to go about with code organization, but I need a variable defined in Server to be able to be read and modified in real time in Services and PacketLib. On top of it, I have 8 of these variables across 3 scripts.

How would one go about putting all imported scripts in the same 'namespace', removing the need for the bogus recursive imports, and allowing for a 'one variable across infinite scripts' execution model of say, C#?

1

There are 1 answers

2
Hisagr On

There shouldn't be any issue with recursive imports.

import' and 'from xxx import yyy' are executable statements. They execute when the running program reaches that line.

If a module is not in sys.modules, then an import creates the new module entry in sys.modules and then executes the code in the module. It does not return control to the calling module until the execution has completed.

If a module does exist in sys.modules then an import simply returns that module whether or not it has completed executing. That is the reason why cyclic imports may return modules which appear to be partly empty.