Modules
A module is a file with a ".py" extension and contains Python code. They can define functions, variables, classes, and can also include runnable code.
You can use modules that are already included when you install Python, from files that you write yourself, or come from a 3rd-party source (usually PyPi). You just have to import
it (and, if necessary, install it first).
import
import
Import a module
Import a specific object from a module
Import more than one specific object from a module
Give imported objects an alternative name
Import all objects from a module
Writing your own modules
Any Python file you write is already a module and any identifiers in your file (variables, functions, classes) are automatically "exported".
When your module gets imported by another file, all code in it will execute as if it were run as a standalone script (i.e. running a script in the command line python3 my_script.py
). Most of the time, you don't want this so it's good practice to only run code when your file was explicitly executed as a standalone script and not imported. You do that by including this block of code at the bottom of your file:
Last updated
Was this helpful?