It's pretty well-known (and documented in PEP8) that import statements should be placed at the top of a Python module, which is what I usually do. However, in my current case, I need to import a module (call it module_a) that gets created when another module (call it module_b) gets run, so it won't work to have import module_a at the top of module_b (which needs to create module_a before importing it).
The solution that I have implemented to solve this is to import module_a inside of a function, after declaring global module_a. As far as I can tell, this works as I want it to.
# In module_b
def create_module_a():
# Creates module_a.py
def import_module_a():
global module_a
import module_a
Part 1 of my question, then, is: Is there a way to do what I want to do and not have an import in the function? Is there a way to adhere to PEP8? One potential solution that I've thought of so far is to have another module, module_c, create module_a before module_b is run and imports module_a... but I'm not even sure that this would even work in my situation, and it would most likely complicate things, at least in the short term.
Part 2 of my question has to do with this statement found in the Python documentation:
Names listed in a global statement must not be defined as formal parameters or in a for loop control target, class definition, function definition, or import statement.
Does the last part of this statement mean that a global name must not be imported, or does it mean that one must not do something like import some_module as module_a, where module_a is declared global?
If the former is true, then what is an alternative to having import_module_a() in module_b?