Python: `from x import *` not importing everything

2020-02-10 06:29发布

I know that import * is bad, but I sometimes use it for quick prototyping when I feel too lazy to type or remember the imports

I am trying the following code:

from OpenGL.GL import *

shaders.doSomething()

It results in an error: `NameError: global name 'shaders' is not defined'

If I change the imports:

from OpenGL.GL import *
from OpenGL.GL import shaders

shaders.doSomething()

The error disappears. Why does * not include shaders?

3条回答
甜甜的少女心
2楼-- · 2020-02-10 06:53

I learned this from my own situation. A module did not automatically import along with the rest of the package. Before that experience my mistaken understanding was that every packages's modules automatically import from an import x or a from x import *. They don't.

Beginners might expect EVERYTHING to import under those calls, I believe. But the following GUI programming code, which is common, demonstrates that that's not the case:

from tkinter import * 
from tkinter import ttk

In the above example, module ttk doesn't import automatically along with the rest of the tkinter package, for instance.

The explanation that I've been told is as follows: when you use from x import *, you actually only imported things in your-python-location/lib/x/__init__.py

Packages are folders. Modules are files. If the import calls for specific files then the package folder's __init_.py will enumerate the specific files to import.

查看更多
Explosion°爆炸
3楼-- · 2020-02-10 07:08

If shaders is a submodule and it’s not included in __all__, from … import * won’t import it.

And yes, it is a submodule.

查看更多
姐就是有狂的资本
4楼-- · 2020-02-10 07:18

shaders is a submodule, not a function.

The syntax from module import something doesn't import submodules (Which, as another answer stated, not defined in __all__).

To take the module, you'll have to import it specifically:

from OpenGL.GL import shaders

Or, if you only want to have a few functions of shaders:

from OpenGL.Gl.shaders import function1, function2, function3

And if you want to have all the functions of shaders, use:

from OpenGL.Gl.shaders import *

Hope this helps!

查看更多
登录 后发表回答