Python: `from x import *` do not import all

I know that import * bad, but I sometimes use it for rapid prototyping, when it seems too lazy to enter or remember import

I am trying to execute the following code:

 from OpenGL.GL import * shaders.doSomething() 

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

If I change the import:

 from OpenGL.GL import * from OpenGL.GL import shaders shaders.doSomething() 

The error will disappear. Why does * not include shaders ?

+6
source share
3 answers

shaders is a submodule, not a function.

The syntax from module import something does not import submodules (which, as said in another answer, are not defined in __all__ ).

To take a module, you will need to import it specifically:

 from OpenGL.GL import shaders 

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

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

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

 from OpenGL.Gl.shaders import * 

Hope this helps!

+3
source

If shaders is a submodule and is not included in __all__ , from … import * does not import it.

And yes, this is a submodule.

+8
source

I learned this from my situation. The module was not automatically imported along with the rest of the package. Prior to this experiment, I mistakenly understood that each package module is automatically imported from import x or from x import * . They do not do this.

Beginners can expect EVERYTHING to import these calls, I reckon. But the following GUI code, which is generic, demonstrates that this is not the case:

 from tkinter import * from tkinter import ttk 

In the above example, the ttk module ttk not automatically import along with the rest of the tkinter package, for example.

The explanation I was told about is this: when you use from x import * , you only actually import things in your-python-location/lib/x/__init__.py

Packages are folders. Modules are files. If the import calls specific files, the __init_.py package __init_.py will list specific files for import.

0
source

Source: https://habr.com/ru/post/957758/


All Articles