TildAliceWhy from module import * Crashes Inside Functions import * works fine at module level. Put...
from module import * Crashes Inside Functions
import * works fine at module level. Put it inside a function, and Python throws SyntaxError: import * only allowed at module level. The error message is clear, but the why is less obvious—and the confusion deepens when you try similar namespace tricks that do work at module level.
I hit this when refactoring a CLI tool that dynamically loaded plugins. The original code used exec() with import * inside a function to inject plugin symbols. It worked—badly. The moment I tried cleaning it up with a proper import statement, Python refused. Here's what actually happens under the hood, and why Python's compiler blocks this pattern before your code even runs.
At module level, from math import * dumps every public name from math into your global namespace. Python handles this at import time—the interpreter knows exactly which names exist before any code runs.
Continue reading the full article on TildAlice