0% found this document useful (0 votes)
7 views5 pages

How Import Works in Python Notes

Importing in Python allows you to load code from modules into your script, enabling the use of functions and variables defined in those modules. You can import entire modules, specific functions, or use wildcards, and you can also rename modules with the 'as' keyword. Python's import system includes a search mechanism for locating modules, caching for efficiency, and the ability to create your own modules and packages.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views5 pages

How Import Works in Python Notes

Importing in Python allows you to load code from modules into your script, enabling the use of functions and variables defined in those modules. You can import entire modules, specific functions, or use wildcards, and you can also rename modules with the 'as' keyword. Python's import system includes a search mechanism for locating modules, caching for efficiency, and the ability to create your own modules and packages.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

How importing in Python works :-

Importing in Python is the process of loading code from a Python module into the current script.
This allows you to use the functions and variables defined in the module in your current script,
as well as any additional modules that the imported module may depend on.

To import a module in Python, you use the import statement followed by the name of the
module. For example, to import the math module, which contains a variety of mathematical
functions, you would use the following statement:

import math
Once a module is imported, you can use any of the functions and variables defined in the
module by using the dot notation. For example, to use the sqrt function from the math module,
you would write:

import math
result = math.sqrt(9)
print(result) # Output: 3.0

from keyword

You can also import specific functions or variables from a module using the from keyword. For
example, to import only the sqrt function from the math module, you would write:

from math import sqrt


result = sqrt(9)
print(result) # Output: 3.0
You can also import multiple functions or variables at once by separating them with a comma:

from math import sqrt, pi


result = sqrt(9)
print(result) # Output: 3.0
print(pi) # Output: 3.141592653589793

importing everything

It's also possible to import all functions and variables from a module using the * wildcard.
However, this is generally not recommended as it can lead to confusion and make it harder to
understand where specific functions and variables are coming from.

from math import *


result = sqrt(9)
print(result) # Output: 3.0
print(pi) # Output: 3.141592653589793
Python also allows you to rename imported modules using the as keyword. This can be useful if
you want to use a shorter or more descriptive name for a module, or if you want to avoid naming
conflicts with other modules or variables in your code.

The "as" keyword

import math as m
result = m.sqrt(9)
print(result) # Output: 3.0
print(m.pi) # Output: 3.141592653589793

The dir function

Finally, Python has a built-in function called dir that you can use to view the names of all the
functions and variables defined in a module. This can be helpful for exploring and
understanding the contents of a new module.

import math
print(dir(math))
This will output a list of all the names defined in the math module, including functions like sqrt
and pi, as well as other variables and constants.

In summary, the import statement in Python allows you to access the functions and variables
defined in a module from within your current script. You can import the entire module, specific
functions or variables, or use the * wildcard to import everything. You can also use the as
keyword to rename a module, and the dir function to view the contents of a module.

AI Overview :-
Python's import system is how you bring code from other modules into your current
program. Think of it like borrowing tools from different toolboxes to complete your project.

Basic Import Mechanics


When you write import math, Python:

1. Searches for a file called math.py (or a compiled module)


2. Executes that file's code
3. Creates a namespace object containing everything from that module
4. Binds it to the name math in your current scope
python
import math
print(math.pi) # Access pi from the math module

Different Import Styles


Standard import:

python
import os
os.path.join('folder', 'file.txt')

Import specific items:

python
from math import pi, sqrt
print(pi) # No need for math.pi

Import with alias:

python
import numpy as np
import matplotlib.pyplot as plt

Import everything (generally discouraged):

python
from math import * # Brings all names into current namespace

How Python Finds Modules


Python searches in this order:

1. Current directory
2. PYTHONPATH environment variable directories
3. Standard library directories
4. Site-packages (where pip installs go)

You can see the search path with:

python
import sys
print(sys.path)
Module Loading Process
The first time you import a module, Python:

• Compiles it to bytecode (creates .pyc files)


• Executes the module code
• Caches it in sys.modules

Subsequent imports just retrieve from the cache - the module code doesn't run again.

Creating Your Own Modules


Any .py file can be a module:

mymodule.py:

python
def greet(name):
return f"Hello, {name}!"

PI = 3.14159

main.py:

python
import mymodule
print(mymodule.greet("Alice"))
print(mymodule.PI)

Packages
Packages are directories containing multiple modules. They need an __init__.py file (can be
empty):

mypackage/
__init__.py
module1.py
module2.py
subpackage/
__init__.py
module3.py
python
import mypackage.module1
from mypackage.subpackage import module3
Common Gotchas
Circular imports: When modules import each other, causing infinite loops. Solution: restructure
code or use local imports.

Mutable defaults in modules: Module-level code runs once, so mutable objects are shared:

python
# In mymodule.py
shared_list = [] # This persists across imports!

Relative vs absolute imports: In packages, use explicit relative imports:

python
from . import sibling_module # Same package
from ..parent import uncle_module # Parent package

The key insight is that import isn't just including code - it's creating objects that contain that
code's namespace, which is why you can inspect modules, reload them, and even modify them
at runtime

You might also like