Code Reference

Import and export

Python · Reference cheat sheet

Import and export

Python · Reference cheat sheet


📋 Overview

Python modules are .py files (or packages with __init__.py). import loads and binds names; there is no separate export keyword—public API is whatever you define and optionally list in __all__. Prefer absolute imports; use relative imports inside packages.

🔧 Core concepts

FormMeaning
import mathBind module name
from math import sqrtBind selected names
from math import sqrt as sAlias
from pkg import moduleSubmodule
from . import siblingRelative (package only)
from .sibling import xRelative name
__all__Names exported by from pkg import *
Entry pointif __name__ == "__main__":

Search path: current package, PYTHONPATH, site-packages. Circular imports usually mean you should restructure or lazy-import inside functions.

💡 Examples

Package layout:

mypkg/
  __init__.py
  utils.py
  api.py
# mypkg/__init__.py
from .api import Client

__all__ = ["Client"]
# mypkg/api.py
from .utils import normalize

class Client:
    def get(self, key: str) -> str:
        return normalize(key)
# app.py
from mypkg import Client
# or: from mypkg.api import Client

Selective import and alias:

import json
from pathlib import Path
from collections import defaultdict as dd

data = json.loads(Path("data.json").read_text(encoding="utf-8"))

Script vs library:

# tools/cli.py
def main() -> None:
    print("run")

if __name__ == "__main__":
    main()

Lazy import (avoid cycles / heavy deps):

def dump(obj: object) -> str:
    import json  # local import
    return json.dumps(obj)

⚠️ Pitfalls

  • from module import * pollutes namespaces; avoid outside REPL/__init__ re-exports.
  • Shadowing stdlib names (json.py, random.py) breaks imports.
  • Relative imports fail when a file is run as a script (python pkg/mod.py); use -m.
  • Mutating sys.path in app code is fragile—fix packaging instead.
  • Side effects at import time (DB connect, network) make testing and startup painful.

On this page