Python Cheatsheet
Modules and Packages
Use this Python reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.
Importing Modules
import math # import module import math as m # alias from math import sqrt # import specific name from math import sqrt, pi, floor # multiple names from math import * # import all public names (avoid) from math import sqrt as sq # import with alias # Usage math.sqrt(16) # 4.0 sqrt(16) # 4.0 (from ... import) m.sqrt(16) # 4.0 (alias)
Import System Behavior
# import executes the module file on first import # subsequent imports return the cached module from sys.modules import sys sys.modules["math"] # cached module object "math" in sys.modules # True after first import # Force reload (development) import importlib importlib.reload(my_module) # Get module path import math math.__file__ # '/usr/lib/python3.x/lib-dynload/math.cpython-3x.so' math.__name__ # 'math' math.__doc__ # module docstring
Module Search Path
import sys sys.path # list of directories Python searches for modules # Add to path at runtime sys.path.insert(0, "/path/to/my/modules") # Or set PYTHONPATH env variable before running Python
Creating a Module
Any .py file is a module. The module name is the filename without .py.
# mymodule.py """My module.""" __version__ = "1.0.0" __author__ = "Alice" def helper(): ... class MyClass: ... # Guard: code here only runs when script is run directly if __name__ == "__main__": helper()
# Importing mymodule.py import mymodule mymodule.helper() mymodule.__version__
__name__ and __main__
# In a module file: print(__name__) # Outputs "mymodule" when imported # Outputs "__main__" when run directly: python mymodule.py if __name__ == "__main__": # Only runs when this file is the entry point main()
Packages
A package is a directory with an __init__.py file.
mypackage/
__init__.py
module_a.py
module_b.py
subpackage/
__init__.py
module_c.py# __init__.py controls what 'import mypackage' exposes # mypackage/__init__.py from .module_a import ClassA # re-export from .module_b import helper # re-export # Importing import mypackage from mypackage import ClassA from mypackage.module_b import helper from mypackage.subpackage.module_c import something
Relative Imports
Only valid inside packages (not in scripts run directly).
# Inside mypackage/module_b.py from . import module_a # same package from .module_a import ClassA # specific name from same package from .. import other_pkg # parent package from ..sibling import func # sibling package
__init__.py Patterns
# Control public API with __all__ __all__ = ["ClassA", "helper"] # what `from pkg import *` exports # Lazy imports for large packages def __getattr__(name): if name == "heavy_module": import mypackage.heavy_module as m return m raise AttributeError(f"module has no attribute {name!r}") # Package version __version__ = "2.1.0"
Namespace Packages (PEP 420)
A directory without __init__.py becomes a namespace package — useful for splitting a package across multiple directories or distributions.
# No __init__.py needed — Python 3.3+ # mypkg/ can span multiple directories on sys.path
Installing and Managing Packages
# pip commands (run in terminal, not Python) # pip install requests # pip install requests==2.28.0 # pip install "requests>=2.25,<3" # pip install -r requirements.txt # pip uninstall requests # pip list # pip show requests # pip freeze > requirements.txt # pip install --upgrade requests # pip install -e . (editable/development install)
importlib — Programmatic Imports
import importlib # Import by string name mod = importlib.import_module("json") mod.dumps({"a": 1}) # Import submodule submod = importlib.import_module(".encoder", package="json") # Reload importlib.reload(mod) # Check if importable importlib.util.find_spec("numpy") # None if not installed # Import from file path spec = importlib.util.spec_from_file_location("mymod", "/path/to/mymod.py") mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod)
Virtual Environments
# Create (built-in) # python -m venv .venv # Activate # source .venv/bin/activate (Unix/macOS) # .venv\Scripts\activate (Windows) # Deactivate # deactivate # Using uv (fast modern alternative) # uv venv # uv pip install requests # uv pip freeze
__all__ and Public API
# module.py __all__ = ["PublicClass", "public_func"] # defines public API class PublicClass: ... def public_func(): ... def _private(): ... # convention: underscore = private # Only PublicClass and public_func are exported with `from module import *` # _private is always accessible by direct import; just hidden from *
pkgutil and pkg_resources
import pkgutil # Iterate over all importable modules for importer, modname, ispkg in pkgutil.iter_modules(): print(modname) # Iterate within a package import mypackage for importer, modname, ispkg in pkgutil.iter_modules(mypackage.__path__): print(modname) # Access package data files import importlib.resources as resources # Python 3.9+ # Read a data file bundled inside a package text = resources.read_text("mypackage", "data.txt") path = resources.files("mypackage") / "data.txt" content = path.read_text()
Module Attributes
| Attribute | Description |
|---|---|
__name__ | "__main__" if script, else module name |
__file__ | Absolute path to the .py file |
__doc__ | Module docstring |
__package__ | Package name (or "" for top-level) |
__spec__ | Import spec (loader info) |
__path__ | Package search path (packages only) |
__all__ | Public API list for * imports |
__version__ | Convention for package version |