13

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?

varesa
  • 2,399
  • 7
  • 26
  • 45

3 Answers3

10

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

And yes, it is a submodule.

rninty
  • 1,072
  • 6
  • 10
5

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!

aIKid
  • 26,968
  • 4
  • 39
  • 65
  • Interesting... then how come doing something like `from urllib import *` imports the `parse` submodule, but not the other submodules, like `request`? – Makonede Feb 17 '21 at 18:14
  • It could be that `parse` is included in `__all__`, see the answer just below > – aIKid Feb 18 '21 at 14:24
0

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.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
user12711
  • 693
  • 1
  • 7
  • 21