Close

Essential Python Module Code

Essential Python Module Code

This is a cheat sheet for modules in Python. It provides examples for common module use and creation.

If you are doing a coding interview in Python, it is recommended to know all of these items, or to keep this list nearby.

It’s also a handy list at work, for when some syntax has slipped your mind. Module syntax changes drastically, and also in subtle ways, between languages, thus sometimes it’s nice to have a quick reference available.

Importing

# Import a specific symbol from a module
from random import randint
print( randint(5,10) )

# Import multiple symbols from a module
from random import randint, choice

# Import a module as a whole
import math
print( math.cos( math.pi ) )

# Import a module under a different name
import itertools as it
print( list( it.islice( it.cycle( 'ABCD' ), 10 ) ) )

# Import all symbols from a module
from typing import *
Vector = List[int]

Creating

A module is a directory with an __init__.py file.

# An __init__.py defines a directory as a module
# It can be empty, but typically includes common useful classes from a module

These can be imported by the name of the directory. Directories within the directory where python is run are automatically added to the search path.

import sample_module
from sample_module.common import *

Visibility

By default, all symbols without leading underscores are exported.

# common.py
def _this_is_hidden():
	print( "You can't see this" )
	
def this_is_public():
	print( "This is a public function") 

A list of explicit symbols can be provided with __all__.

__all__ = [ 'User', 'Account' ]

Relative Imports

Within a package you can import another module with a relative path.

from .types import User
from . import common
from .. import upper
from ..upper import UpperClass

Executable Module

To make a module executable define a __main__.py file.

# __main__.py
print( "This is the main function" )

Then run with python -m sample_module

Edaqa Mortoray

An avid writer and expert programmer. He’s been on both sides of the interview table countless times and enjoys sharing his experiences. https://edaqa.com/