def mathImport():
from math import *
I dont know if it is possible and if it isn't, is there a other way to do something like this?
def mathImport():
from math import *
I dont know if it is possible and if it isn't, is there a other way to do something like this?
Instead of importing everything, just bring in what you need
def myfunction():
from math import pi, tan
# work with imports
There is no way to use *
-imports in nested scopes – i.e. functions or classes. Since variable scope outside of the module global
namespace is determined at compile time, the runtime name-binding of *
-imports does not work.
7.11. The import statement
The wild card form of import —
from module import *
— is only allowed at the module level. Attempting to use it in class or function definitions will raise a SyntaxError.
Explicitly import the names needed:
def mathImport():
from math import ceil
...
According to Python import
docs the use of from module import *
is a wild card form and is not allowed to be used in class or function definition. In addition, it isn't a good practice to use this syntax, see this documentation to understand the risks.
you cannot import modules in a function and use them globally, you also cannot import from a string.
There is a module called import lib that you could use to programmatically import modules by string.
https://docs.python.org/3/library/importlib.html#module-importlib
>>> module = importlib.import_module("time", ".*")
>>> module.time()
1619787987.921014
>>>