Tutorial by Examples

Use the import statement: >>> import random >>> print(random.randint(1, 10)) 4 import module will import a module and then allow you to reference its objects -- values, functions and classes, for example -- using the module.name syntax. In the above example, the random module...
Instead of importing the complete module you can import only specified names: from random import randint # Syntax "from MODULENAME import NAME1[, NAME2[, ...]]" print(randint(1, 10)) # Out: 5 from random is needed, because the python interpreter has to know from which resource it...
from module_name import * for example: from math import * sqrt(2) # instead of math.sqrt(2) ceil(2.7) # instead of math.ceil(2.7) This will import all names defined in the math module into the global namespace, other than names that begin with an underscore (which indicates that the wri...
Modules can have a special variable named __all__ to restrict what variables are imported when using from mymodule import *. Given the following module: # mymodule.py __all__ = ['imported_by_star'] imported_by_star = 42 not_imported_by_star = 21 Only imported_by_star is imported when usi...
Python 2.x2.7 To import a module through a function call, use the importlib module (included in Python starting in version 2.7): import importlib random = importlib.import_module("random") The importlib.import_module() function will also import the submodule of a package directly: c...
If you want to import a module that doesn't already exist as a built-in module in the Python Standard Library nor as a side-package, you can do this by adding the path to the directory where your module is found to sys.path. This may be useful where multiple python environments exist on a host. im...
Some recommended PEP8 style guidelines for imports: Imports should be on separate lines: from math import sqrt, ceil # Not recommended from math import sqrt # Recommended from math import ceil Order imports as follows at the top of the module: Standard libr...
from module.submodule import function This imports function from module.submodule.
The __import__() function can be used to import modules where the name is only known at runtime if user_input == "os": os = __import__("os") # equivalent to import os This function can also be used to specify the file path to a module mod = __import__(r"C:/path/...
When using the interactive interpreter, you might want to reload a module. This can be useful if you're editing a module and want to import the newest version, or if you've monkey-patched an element of an existing module and want to revert your changes. Note that you can't just import the module ag...

Page 1 of 1