1.1 Getting to Know Modules
A module in Python is basically a file with a .py extension that contains code. Modules help break down big chunks of code into smaller, more manageable pieces. Each module can have functions, classes, and variables, and can even run some code when it's imported.
Example of a Simple Module
Let's create a module called mymodule.py
:
# mymodule.py
def greet(name):
return f"Hello, {name}!"
pi = 3.14159
Now this module can be imported and used in another file.
1.2 Importing Modules
Python gives you a bunch of ways to import modules. Let's go through them.
Importing the Whole Module
The syntax for this operation looks like:
import module
This method imports the entire module, letting you use its functions and variables by prefixing them with the module's name.
import module
print(module.greet("Alice")) # Output: Hello, Alice!
print(module.pi) # Output: 3.14159
We've done something like this before with the math
module, remember?
import math
print(math.ceil(13 / 7)) # rounding up
print(math.floor(13 / 7)) # rounding down
Importing Specific Elements from a Module
You don't have to import everything; you can just import specific things from a module. The syntax looks like this:
from module import func, var
This method imports only certain functions, classes, or variables from a module, so you can use them without the module's name.
from mymodule import greet, pi
print(greet("Bob")) # Output: Hello, Bob!
print(pi) # Output: 3.14159
Importing a Module with an Alias
The syntax for this operation looks like:
import module as alias
This method lets you import a module and give it a different name. This can be handy for shortening long module names or resolving name conflicts.
import mymodule as mm
print(mm.greet("Charlie")) # Output: Hello, Charlie!
print(mm.pi) # Output: 3.14159
Importing Everything from a Module
The syntax for this operation looks like:
from module import *
This method imports all functions, classes, and variables from a module, letting you use them without the module's name. But caution: this can cause name conflicts and make your code harder to read.
from mymodule import *
print(greet("Dave")) # Output: Hello, Dave!
print(pi) # Output: 3.14159
1.3 Under the Hood of Module Importing
The Search Order for Modules
When you import a module, Python looks for it in a specific order:
- Current Directory: Python first checks the current directory where the script was run.
-
Environment Variable
PYTHONPATH
: If it's not found in the current directory, Python looks in directories listed in thePYTHONPATH
environment variable. -
Standard Directories: If it's still not found, Python checks standard directories like those in
sys.path
.
Example:
import sys
for path in sys.path:
print(path)
Global and Local Import
You can import modules globally (at the start of the file) or locally (inside a function or method).
Global Import
A global import is done at the start of a file, making the module available throughout the file.
import math
def calculate_circle_area(radius):
return math.pi * radius ** 2
Local Import
A local import is done inside a function or method, making the module available only within that function or method.
def calculate_square_root(x):
import math
return math.sqrt(x)
print(calculate_square_root(16))
Local imports can be useful for reducing module load times or avoiding name conflicts.
1.4 Dynamic Import
Dynamic importing lets you import modules while your program is running. This can be handy when you need to import modules based on user input or other dynamic conditions.
The syntax for this operation looks like:
module = __import__("module")
For an example, let's import the math
module this way.
module_name = "math"
module = __import__(module_name)
print(module.sqrt(16)) # Output: 4.0
Working with further code is similar to using import as
, where the math
module is given the alias module
.
1.5 Accessing Module Attributes Using getattr
The getattr
function allows you to dynamically fetch attributes from a module (or any object). It's handy when attribute names are unknown beforehand or might change during runtime.
Syntax for the getattr
function:
getattr(object, name, default = None)
Where object
is the object you want to get the attribute from, name
is a string with the attribute's name, and default
is the value returned if the attribute doesn't exist. The default value for default
is None
.
Example using the getattr
function:
import math
# Get the sqrt attribute from the math module
sqrt_function = getattr(math, 'sqrt')
print(sqrt_function(25)) # Output: 5.0
# Try to get a non-existent attribute, return a default value instead
non_existent_attr = getattr(math, 'non_existent', 'default_value')
print(non_existent_attr) # Output: default_value
In this example, we use getattr
to get the sqrt
function from the math
module, then call it to compute the square root of 25. If the attribute name doesn't exist, it returns the default value default_value
.
GO TO FULL VERSION