1
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?

timgeb
  • 76,762
  • 20
  • 123
  • 145
Oskar_GER
  • 25
  • 6
  • ``` def projectX(): ^ SyntaxError: import * only allowed at module level ``` i get this error – Oskar_GER Apr 30 '21 at 12:53
  • 1
    You can just use the methods from math `import math`; then it's clearer where they come from! – ti7 Apr 30 '21 at 12:55
  • 3
    Is `SyntaxError: import * only allowed at module level` not clear somehow? – timgeb Apr 30 '21 at 12:55
  • 1
    Why not just import the names you actually need? – MisterMiyagi Apr 30 '21 at 12:55
  • @timgeb That's their question though: "_is there a way to_"? (even though it's practically a bad idea because it throws away namespace information) – ti7 Apr 30 '21 at 12:55
  • What are you trying to do? It sounds like you've arrived at trying to `import *` in a function to solve a problem, but that is not the correct solution – C.Nivs Apr 30 '21 at 12:57

4 Answers4

1

Instead of importing everything, just bring in what you need

def myfunction():
    from math import pi, tan
    # work with imports
ti7
  • 16,375
  • 6
  • 40
  • 68
1

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
  ...
MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
  • this is probably the best answer because it has both how to get what's really wanted sensibly and also why a wildcard import won't work – ti7 Apr 30 '21 at 13:04
0

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Janio Lima
  • 61
  • 3
-1

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
>>> 
a1cd
  • 17,884
  • 4
  • 8
  • 28