Modules and Packages
Comparison between JavaScript and Python
The information comes from the Udemy course "Become an AI Engineer: Python for JavaScript Developers" by
Vilva Athiban
| Feature |
JavaScript |
Python |
| Importing |
import _ from "lodash"; // whole module
import { sqrt } from "./mathUtils.js"; // a specific export
import * as utils from "./utils.js"; // namespace / alias
// --- Exporting (lib/print.js) ---
export function printLine() {
console.log("hello world");
}
// or a barrel file (index.js) re-exporting:
// export { printLine } from "./print.js";
// --- Relative imports use ./ and ../ ---
import { a } from "./sameFolder.js";
import { b } from "../parentFolder.js";
import { c } from "./folder1/folder2.js";
// Node.js ships with very little;
// you install most utils from npm,
// so package.json tends to grow large.
|
import math # whole module
from math import sqrt # a specific function
import math as m # alias with `as`
print(math.sqrt(10))
print(sqrt(4)) # 2.0
print(m.sqrt(16)) # 4.0
# Best practice:
# import only what you need (from module import thing),
# not the whole module
# — same idea as JS named imports.
# --- Exporting:
# a package is a folder with an __init__.py ---
# This is very similar to a React component's index.js barrel file.
#
# lib/
# __init__.py <-- like index.js
# print.py <-- def print_line(): print("hello world")
#
# lib/__init__.py:
# from .print import print_line # relative import (leading dot)
# __all__ = ["print_line"] # controls what
# `from lib import *` exposes
#
# workspace.py:
# from lib import print_line
# print_line() # "hello world"
# --- Relative imports use dots, NOT slashes ---
# from .print import x # same folder (JS: ./)
# from ..parent import y # parent folder (JS: ../)
# from .folder1.folder2 import z # subfolder (JS: ./folder1/folder2)
# Python is "batteries included" —
# the standard library covers a huge amount,
# so you reach for pip far less often than npm.
|