The import system in Python is used to load modules into your program. A module is a file containing Python code and definitions, such as functions, classes, and variables.
Here’s a quick overview of how the import system works:
1. Importing a module: Use the `import` keyword to import a module into your Python program. Once a module is imported, you can use its functions, classes, etc. in your program. For example, `import math` imports the math module and `math.sqrt()` can be used to find the square root of a number.
1. Importing specific attributes: Use the `from` keyword to import a specific function, class or variable from a module. If only a specific function from the math module is needed, it can be imported individually like so: `from math import sqrt`. Then you can just call `sqrt()` directly.
1. Renaming on import: If the name of function, class or the module itself is long, it can be renamed during the import using the `as` keyword: `import math as m` or `from math import sqrt as sq`. Then, use: `m.sqrt()` or `sq()`.
1. Importing multiple attributes: Multiple attributes can be imported from the module at once: `from math import sqrt, pi, cos`.
1. Import everything from a module: `from math import *` imports everything from the module. This is generally not recommended because it pollutes the namespace and can lead to naming conflicts.
When you import a module, Python searches for the module in the following locations:
- The directory of the input script (or the current directory when no file is specified).
- The directories listed in the PYTHONPATH environment variable (if it is set).
- The installation-dependent default path.
If the searched module is found, it is loaded and run once. If Python cannot find the module, it raises an ImportError exception.