Reputation: 3943
I have a package with two modules in it. One is the __init__
file, and the other is a separate part of the package. If I try from mypackage import separatepart
, the code in the __init__
module is run, which will run unneeded code, slowing down the importing by a lot. The code in separate part won't cause any errors, and so users should be able to directly import it without importing the __init__
module.
Since I can't figure out a way to do this, I thought I should include a function in the __init__
file that does everything so nothing would be done directly, but in order to do this, I would need to have any variables set to be global. Is there any way to tell Python that all variables are global in a function, or to not run the __init__
module?
Upvotes: 0
Views: 293
Reputation: 71064
dthat I know of, there is not way to specify that all variables are global but you can import the module while you are in the module. just make sure that you do it in a function that isn't called at the top level, you are playing with infinite recursion here but a simple use should be safe.
#module.py
foo = bar = 0 # global
def init()
import module as m
m.foo = 1
m.bar = 2 # access to globals
if Since you want to do this in the init
was called at the top level, then you have infinite recursion but it sounds like the whole point of this is to avoid this code running at the top level, so you should be safe.__init__.py
file, just import the top level of the package.
It occurred to me on a walk that there's no problem with recursion here because the top level code will only run once on initial import.
Upvotes: 1