Source: Karla Car on Unsplash
To use code from a module, you need to import it. There are several ways to do this:
This imports the whole module, and you access its contents using the module name as a prefix.
import my_module
my_module.my_function()
print(my_module.my_variable)
You can also assign a shorter alias to the module:
import my_module as mm
mm.my_function()
This imports only the specified functions or variables directly into your namespace, allowing you to use them without the module prefix.
from my_module import my_function, my_variable
my_function()
print(my_variable)
You can also rename imported names:
from my_module import my_function as mf
mf()
While possible, importing everything from a module is generally discouraged as it can lead to naming conflicts and make code harder to understand.
from my_module import * # Avoid this
sys.path
)When you import a module, Python searches for it in a specific order:
PYTHONPATH
environment variable.If Python can't find the module, you'll get a ModuleNotFoundError
.
If your module isn't in the same directory as your script, you have a few options:
sys.path
(Less Recommended)You can add the module's directory to sys.path
within your script:
import sys
sys.path.append('/path/to/my_module') # Avoid hardcoding paths
import my_module
However, this is usually not the best approach for long-term projects.
PYTHONPATH
Environment Variable (Recommended)The preferred way is to add the module's directory to the PYTHONPATH
environment variable. This tells Python to always check that directory for modules. The video explains how to set this up on macOS and Windows.
Python comes with a rich set of built-in modules called the standard library. These modules provide functionality for many common tasks, so you don't have to install them separately.
Examples of standard library modules:
math
: For mathematical functions (e.g., math.sin()
, math.radians()
).datetime
and calendar
: For working with dates and times (e.g., datetime.date.today()
, calendar.isleap()
).os
: For interacting with the operating system (e.g., os.getcwd()
).random
: For generating random numbers and making random choices (e.g., random.choice()
).sys
: Access system-specific parameters and functions, including sys.path
.You can find the location of a standard library module using its __file__
attribute (e.g., os.__file__
).
With a solid understanding of fundamental concepts like data types, conditionals, loops, functions, and modules, you're well-equipped to explore more advanced Python topics. Some potential next steps include: