DEV Community

Switch by Skill
Switch by Skill

Posted on Originally published at switchbyskill.com

Node.js developer learning Python: what carries over, what's new, 30-day plan

What carries over

Node.js concept Python equivalent Why it matters
Event loop & async I/O asyncio event loop, await/async syntax Both runtimes are single‑threaded by default and use non‑blocking I/O. The mental model of “don’t block the thread” stays the same.
Package management pip / venv (or pipenv, poetry) npm install → pip install. Use a virtual environment to isolate dependencies just as you would a node_modules folder.
Modules import / from … import … ES‑modules (import … from …) map directly to Python’s import system. The idea of a file being a module stays.
JSON handling json module (json.loads, json.dumps) JSON.stringify / JSON.parse have direct counterparts.
Environment variables os.getenv, dotenv process.env → os.getenv. Loading a .env file works the same way with python-dotenv.
Testing unittest or pytest npm test → python -m unittest discover or pytest. Test discovery and assertions follow similar patterns.
Logging logging module console.log → logging.info/debug/warning/error. Configurable handlers mirror winston or pino.
REST client requests library fetch/axios → requests.get/post. Same request/response flow, just different API.
Linting / formatting flake8, black eslint/prettier → flake8 (style) and black (auto‑format).
Version control hooks Same git workflow No change; keep using git commit, branch, rebase.

Coding habits that survive

  1. Small, composable functions – Write pure functions, keep side‑effects at the edges.
  2. Explicit error handling – try/catch → try/except. Don’t rely on “undefined” values; raise exceptions early.
  3. Consistent naming – CamelCase for classes, snake_case for functions/variables (just adopt Python’s convention).
  4. Dependency injection – Pass collaborators as arguments; works with any language.

What's new

Python’s syntax and standard library differ enough to feel fresh. Below is a side‑by‑side example that reads a CSV file, filters rows where the status column equals "active", and prints the id field.

// Node.js (ESM)
import { createReadStream } from 'fs';
import { parse } from 'csv-parse';

const stream = createReadStream('data.csv')
  .pipe(parse({ columns: true }))
  .on('data', (row) => {
    if (row.status === 'active') {
      console.log(row.id);
    }
  })
  .on('error', (err) => {
    console.error(err);
  });
Enter fullscreen mode Exit fullscreen mode
# Python 3
import csv

with open('data.csv', newline='') as f:
    reader = csv.DictReader(f)
    for row in reader:
        if row['status'] == 'active':
            print(row['id'])
Enter fullscreen mode Exit fullscreen mode

What changed and why

Aspect Node.js Python Reason
File handling createReadStream (stream API) open with context manager (with) Python encourages deterministic resource cleanup via context managers.
CSV parsing External csv-parse library Built‑in csv module Python’s standard library is richer; many tasks need no third‑party package.
Event‑driven vs. eager iteration Stream emits data events Simple for loop over iterator Python’s iterators are lazy but usually consumed in a straightforward loop, reducing callback boilerplate.
Error handling .on('error', …) on the stream try/except around the block (omitted for brevity) Python centralises error handling with exceptions rather than per‑event listeners.
Variable access row.status (object property) row['status'] (dict key) CSV rows are dictionaries; Python uses bracket notation for dict access.

Other notable differences

  • Indentation matters – No braces; block structure is defined by whitespace.
  • Type hints – Optional static typing via typing module (def func(x: int) -> str:).
  • No null – Use None.
  • List comprehensions & generator expressions – Concise data transformations ([r['id'] for r in rows if r['status'] == 'active']).

Common pitfalls

  1. Mixing indentation styles – Tabs vs. spaces will raise IndentationError. Configure your editor for 4 spaces.
  2. Mutable default arguments – def foo(bar=[]): keeps the same list across calls. Use None and create a new list inside.
  3. Forgot to activate virtual environment – Running pip install globally can corrupt system packages. Always source venv/bin/activate (Unix) or venv\Scripts\activate (Windows).
  4. Assuming == works like === – Python’s == performs value equality, but type coercion is rare; be explicit with is for identity checks.
  5. Over‑using global variables – Python modules are singletons; mutating globals can cause hidden state bugs.
  6. Blocking the event loop – Using synchronous I/O inside an async function blocks the asyncio loop. Prefer aiohttp, aiofiles, or run sync code in a thread pool (loop.run_in_executor).
  7. Incorrect package import paths – Python resolves imports relative to the module not the current working directory. Use absolute imports (from mypkg.utils import helper).

Your 30‑day plan

Week 1 – Foundations

  1. Install Python 3, set up venv, and install black & flake8.
  2. Complete the official “Python Basics” tutorial (variables, control flow, functions).
  3. Write a small CLI that mimics an existing Node script (e.g., a file‑watcher that logs changes).

Mini‑project: Re‑implement a simple “Hello, World” HTTP server using http.server and compare startup time with an Express app.

Week 2 – Asynchrony & Ecosystem

  1. Learn asyncio: create a task, use await, and handle cancellation.
  2. Swap a synchronous requests call for an aiohttp version in a script that fetches multiple URLs concurrently.
  3. Explore package management with pip and poetry (optional).

Mini‑project: Build a tiny URL‑shortener service using FastAPI, store data in an in‑memory dict, and write async endpoint handlers.

Week 3 – Testing, Logging, and Packaging

  1. Write unit tests with pytest; practice fixtures and parametric tests.
  2. Set up structured logging with the logging module and a JSON formatter.
  3. Create a setup.py or pyproject.toml so the mini‑project can be installed with pip install ..

Mini‑project: Add a test suite to the FastAPI URL‑shortener, include CI‑style linting (black --check, flake8), and publish a local wheel.

Week 4 – Production‑ready Patterns

  1. Containerise the FastAPI app with a minimal Dockerfile (use python:slim).
  2. Add graceful shutdown handling (signal.SIGTERM) and health‑check endpoints.
  3. Profile the app with cProfile and identify any blocking calls.

Capstone project: Deploy the container locally with docker compose, expose it on port 8000, and write a small Node.js script that consumes the API to verify cross‑language interoperability.


FAQ

How do I run a Python script in watch mode like nodemon?

Install watchdog (pip install watchdog) and use watchmedo auto-restart --patterns="*.py" -- python your_script.py.

Is there a direct equivalent to process.env?

Yes, use os.getenv('VAR_NAME') or os.environ['VAR_NAME']. The python-dotenv package can load a .env file automatically.

Should I use type hints everywhere?

They are optional but highly recommended for larger codebases; tools like mypy can check them without affecting runtime.

Can I still use JavaScript libraries from Python?

Not directly. For front‑end assets you’d keep the Node toolchain (Webpack, etc.) and serve the built files from a Python web framework.

Keep going

Originally published at switchbyskill.com.

Top comments (0)