to explain this, let's define this function:
def import_math():
import math
import_math()
the above function will import the module math, but only in its local scope, anyone that tries to reference math
outside of it will get a name error, because math
is not defined in the global scope.
any module that is imported is saved into sys.modules so a call to check
import_math()
print("math" in sys.modules)
will print True, because sys.modules caches any module that is loaded anywhere, whether or not it was available in the global scope, a very simple way to define math
in the global scope would then to
import_math()
math = sys.modules["math"]
which will convert it from being only in sys.modules
to being in the global scope, this is just equivalent to
import math
which defines a variable math
in the global scope that points to the module math
.
now if you want to see whether "math" exists in the global scope is to check if it is in the global scope directly.
print("math" in globals())
print("math" in locals())
which will print false if "math" wasn't imported into the global or local scope and is therefore inaccessable.