Modules and Imports
Organizing code across files
Introduction
In this lesson, you'll learn about modules and imports in Python. Coming from JavaScript, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In JavaScript, you're familiar with organizing code across files.
Python has its own approach to organizing code across files, which we'll explore step by step.
The Python Way
Let's see how Python handles this concept. Here's a typical example:
# math_utils.py
PI = 3.14159
def add(a, b): return a + b
class Calculator: pass # ...
# main.py
from math_utils import PI, add
import math_utils
from math_utils import Calculator as Calc
# Import everything (discouraged)
from math_utils import *
# Standard library
import os
import json
from pathlib import Path
# Dynamic import
import importlib
mod = importlib.import_module("math_utils")Comparing to JavaScript
Here's how you might have written similar code in JavaScript:
// math.js
export const PI = 3.14159;
export function add(a, b) { return a + b; }
export default class Calculator { /* ... */ }
// main.js
import Calculator, { PI, add } from "./math.js";
import * as MathLib from "./math.js";
// Dynamic import
const { add: sum } = await import("./math.js");
// CommonJS (Node.js)
const fs = require("fs");
module.exports = { add };You may be used to different syntax or behavior.
Python has no export keyword — everything is importable
You may be used to different syntax or behavior.
from module import name ≈ import { name } from 'module'
You may be used to different syntax or behavior.
import module ≈ import * as module
You may be used to different syntax or behavior.
Packages need an __init__.py file
Step-by-Step Breakdown
1. Named Imports
In Python, every top-level name in a module is automatically public. You import specific names with from.
import { PI, add } from "./math.js";from math_utils import PI, add2. Namespace Import
import module loads the whole module under a namespace.
import * as MathLib from "./math.js";
MathLib.add(1,2);import math_utils
math_utils.add(1, 2)3. Packages
A folder becomes a Python package when it contains an __init__.py file.
// No equivalent — Node uses package.json# mypackage/__init__.py (can be empty)
from mypackage.utils import helperCommon Mistakes
When coming from JavaScript, developers often make these mistakes:
- Python has no export keyword — everything is importable
- from module import name ≈ import { name } from 'module'
- import module ≈ import * as module
Key Takeaways
- No export keyword — everything is public by default
- from module import name for named imports
- Packages = folders with __init__.py