3 ms·
Python can also import only some names from a module: from module import name, name, name and can also run a module import under control of a try/except b
by vram22 8y ago
Python can also import only some names from a module:
from module import name, name, name
and can also run a module import under control of a try/except block, so you can trap the ImportError and do something about it. A typical use is to try to import the C version (for performance) of a module, and if that fails, fall back to the pure Python version of the same module; e.g. cElementTree and ElementTree:
try:
import cElementTree
except ImportError:
import ElementTree
- vram22 8y agoSorry, mistake in the last snippet above, it should really be: try: import cElementTree as ElementTree except ImportError: import ElementTree because otherwise, you have to know which import succeeded, because that changes the name by which you reference the module and the items in it.