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 a module

import datetime

print(datetime.date.today())

Import a specific object from a module

from datetime import date

print(date.today())

Import more than one specific object from a module

from datetime import date, datetime

print(date.today())
print(datetime.now())

Give imported objects an alternative name

from datetime import date as d, datetime as dt

print(d.today())
print(dt.now())

Import all objects from a module

from datetime import *

print(date.today())
print(datetime.now())

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:

if __name__ == '__main__':
    print('Running as a stand-alone script, not a module')
    # Call your functions here

Last updated