01A.11 Coming from PHP, JavaScript or Java: Side by Side
You already know how to program. What you don't know yet is which Python idea corresponds to which idea you already have — and, just as important, which Python behaviours have no equivalent at all and will bite you if you assume they do. This lesson is a phrasebook, not a tutorial: for every big topic it gives you a side-by-side table (concept / PHP / JavaScript / Java / Python), calls out the Python surprises that break newcomers, and shows the same small task written in all four languages so you can see the shape of idiomatic Python. Everything Python in this lesson runs on the standard library alone; the PHP, JavaScript and Java listings are for reading, not running — they are labelled where they appear.
What you'll learn
- How the four languages' runtimes actually work, and why "interpreted vs compiled" is the wrong mental model for all of them
- The Python data model: names as labels on objects, everything-is-an-object, dynamic typing without type juggling, and why there are no
$, no semicolons and no braces - Scope rules (there is no block scope), truthiness and equality (
==vsis), and theNone/null/undefined/NULLzoo - Numbers, strings, booleans, dates and times, and every operator you use daily, mapped one-to-one
- Collections: PHP's everything-array vs Python's
list/tuple/dict/set; JS arrays/objects/Map/Set; Java'sList/Map/Setand streams — plus sorting, copying and iteration - Functions (defaults, keyword args,
*args/**kwargs, closures) and object-oriented Python (classes,__init__,@property,Protocol, dataclasses, enums, dunders) compared with interfaces, traits, records and getters/setters - Error handling (
try/except/finally,raise ... from,with) across checked and unchecked exception models - A preview of async (
asynciovsPromisevsCompletableFuture) — the deep version is Module 01B - The tooling map: Composer/npm/Maven/Gradle vs
uv/pip,pyproject.toml, virtual environments,ruff,pytest - A 40-row idiom translation table, a gallery of Python surprises with real output, the same program in four languages, and a 30-minute fast track that tells you which 01A lessons to skim and which to skip
What you don't need
- Python knowledge — this lesson assumes you know a language well, not Python. If you know none of the three, read 01A.1 first.
- API keys or network access. Everything here is offline and standard-library only. No API key needed.
- PHP, JavaScript or Java installed. Their listings are illustrative translations; you only need to read them.
Setup
You need Python 3.11 or newer and a terminal. The quickest route is uv (as of November 2026 the latest stable Python is 3.15.x; anything from 3.11 up runs every sample here):
curl -LsSf https://astral.sh/uv/install.sh | sh # macOS/Linux; see https://docs.astral.sh/uv/ for Windows
uv python install 3.13
uv run python --versionOr install from python.org or your OS package manager, then run scripts with python3 script.py. The official install pages for each language covered here: PHP, Node.js and Java (or any OpenJDK vendor such as Adoptium). You don't need them installed — this lesson never runs their code.
What you must be able to do after this lesson#
- Explain Python names as labels on objects
- Translate common PHP, JavaScript or Java idioms to Python
- Explain Python truthiness and the difference between == and is
- Pick the right Python collection for what you used before
- Handle errors and resources the Python way
- Follow the 30-minute fast track to get productive
Why this matters for an AI engineer#
Most of the code you will write in Modules 01B to 14 is ordinary Python wearing an LLM hat: dictionaries and lists of records, JSON in and out, functions that call functions, exceptions at trust boundaries, files on disk, async calls to provider APIs. If you can already do those things in PHP/JS/Java, the only new skill is knowing which Python spelling is idiomatic — and which behaviours differ subtly enough to produce silent bugs.
| You'll hear... | You'll understand it after... |
|---|---|
| "It's just dicts and lists of dicts." | Part 3: Collections |
| "The response is a Pydantic model, not a dict." | Part 4.7 (then 01B.6) |
"asyncio.gather is basically Promise.all." |
Part 6 |
"Why did except catch that error?" |
Part 5 |
| "Don't use a mutable default argument." | Part 9 |
| "That closure captured the loop variable." | Part 4.2 and Part 9 |
| "The SDK's types are hints, not validation." | Part 7.5 |
"Why does for line in response.iter_lines() work?" |
Part 3.8 and 03.3 |
| "Port this PHP script to Python." | Part 8 and Part 10 |
| "Which 01A lessons can I skip?" | Part 11 |
Part 1: The mindset map#
1.1 Four runtimes, one job#
The first correction is that "interpreted vs compiled" sorts these languages wrongly. All four turn your source into something the machine runs, and all four have a fast path:
| PHP | JavaScript (Node/browsers) | Java | Python | |
|---|---|---|---|---|
| You write | .php source |
.js/.ts source |
.java source |
.py source |
| First step | Zend compiler → opcodes | V8 parses to bytecode | javac → bytecode (.class) |
CPython compiles to bytecode (.pyc) |
| What runs it | Zend Engine (+ Opcache, + JIT since PHP 8.0) | V8/JSC engine (JIT) | JVM (JIT, optional AOT via GraalVM) | CPython evaluation loop; optional free-threaded build |
| Types | Dynamic, but loosely compared | Dynamic, coerces == |
Static, generics, primitives | Dynamic, but strongly typed |
| Concurrency | One request per process (PHP-FPM); Fibers for cooperative tasks | Single-threaded event loop + worker threads | Real OS threads; virtual threads since Java 21 | Threads + asyncio event loop; the GIL limits CPU parallelism |
The practical consequences for you:
- Python is not "slow because interpreted". CPython turns source into bytecode and runs a tight evaluation loop; NumPy, and the provider SDKs you will call, do their heavy work in C. The performance advice that matters is algorithm and I/O, not "interpreted".
"1" + 1shows the four philosophies in one expression. In JS it gives"11"(string concatenation); in Java it also gives"11"— Java's+is overloaded and concatenates whenever aStringoperand is involved (JLS §15.18.1); in PHP"1" + 1gives2(numeric strings are juggled); in Python it raisesTypeError. Notice the inversion: JS and Java silently produce"11", PHP silently produces2, and only Python refuses — the strongest possible argument for explicit conversion. You will see this demonstrated in 2.4.- Java is the only one of the four with checked exceptions and real threads by default. Python sits between JS and Java: exceptions like JS (unchecked), threads like Java but mediated by the GIL.
1.2 Everything is an object; names, not variables#
In PHP, JS and Java, a variable is a box with a type. In Python a variable is a name — a label attached to an object. Assignment never copies; it re-points the name:
# names.py
tickets = ["a", "b"]
alias = tickets # alias is ANOTHER NAME for the same list
alias.append("c")
print(tickets) # ['a', 'b', 'c'] — both names see the change
print(tickets is alias) # True — one object, two names
tickets = ["x"] # rebinding: tickets now names a DIFFERENT list
print(alias) # still ['a', 'b', 'c']['a', 'b', 'c']
True
['a', 'b', 'c']This is why Python's "variables" can change type freely (x = 5 then x = "five") while the objects themselves are strongly typed: an int object can't suddenly become a str. Dynamic typing describes the name; strong typing describes the object.
flowchart LR
subgraph before ["After: tickets = ['a','b']"]
N1["name: tickets"] --> O1["list object<br/>['a', 'b']"]
end
subgraph after ["After: alias = tickets; alias.append('c')"]
N2["name: tickets"] --> O2["same list object<br/>['a', 'b', 'c']"]
N3["name: alias"] --> O2
end
subgraph rebind ["After: tickets = ['x']"]
N4["name: tickets"] --> O3["new list<br/>['x']"]
N5["name: alias"] --> O2
end
before -.-> after -.-> rebind1.3 No $, no semicolons, no braces: whitespace is syntax#
Python has no sigils, no statement terminators and no block delimiters. A block is "the lines indented more than the line that opened it". Four spaces per level is the universal convention (PEP 8):
def classify(priority):
if priority == "high":
return "page_on_call"
elif priority == "low":
return "backlog"
return "triage"The same code in the other three, for contrast (illustrative — not runnable here):
<?php
function classify(string $priority): string {
if ($priority === "high") { return "page_on_call"; }
if ($priority === "low") { return "backlog"; }
return "triage";
}function classify(priority) {
if (priority === "high") return "page_on_call";
if (priority === "low") return "backlog";
return "triage";
}static String classify(String priority) {
return switch (priority) {
case "high" -> "page_on_call";
case "low" -> "backlog";
default -> "triage";
};
}Things to unlearn:
| Habit | Python reality |
|---|---|
var $x = 1; / $this->x |
x = 1, self.x (in methods) |
let/const/var |
Just name = value; no const — convention is UPPER_CASE names |
; at end of statement |
Newline ends the statement; ; exists but is almost never used |
{ } around blocks |
Indentation (4 spaces) |
-> / => / . for member access |
. for attributes and method calls: obj.method() |
\n line continuation \ |
Implicit inside brackets; explicit \ works but is rare |
| camelCase variables | snake_case for variables/functions, PascalCase for classes, UPPER_CASE for constants |
1.4 Scope: there is no block scope#
This surprises everyone coming from Java or modern JavaScript. In Python, if, for, while, with and try blocks do not create scope. Only four things do: the module, a function, a class, and (since Python 3) each comprehension:
# scope_demo.py
x = "module level"
def f():
x = "function local" # new local, shadows the global inside f only
if True:
y = "still function scope" # NOT a new scope — y is local to f
return y
print(f())
print(y if "y" in dir() else "y is not module-level") # y never escaped f
for i in range(3):
pass
print("i =", i) # i = 2 — loop variables leak into the enclosing scope!still function scope
y is not module-level
i = 2Contrast with the other three, where { } is the scope boundary:
Block { } scope? |
Loop variable leaks? | |
|---|---|---|
| PHP | No — function scope only (like Python, minus comprehensions) | Yes, $i persists |
| JavaScript | let/const are block-scoped; var is function-scoped |
let i does not leak; var i does |
| Java | Yes — every { } block |
No |
| Python | No block scope at all | Yes, always |
Name resolution inside a function follows LEGB: Local → Enclosing function → Global → Builtins. You rarely need the rules explicitly, but two consequences matter daily:
- A function sees the current value of a global at call time, not def time (demonstrated in 9.3).
- Assigning to a name anywhere in a function makes it local throughout that function — reading it before the assignment raises
UnboundLocalError, not the global value. The fix isglobal x(rarely right) or pass it as an argument (usually right).
1.5 Dynamic typing, but no type juggling#
PHP and JavaScript will silently convert types for you: "1" + 1 is 2 in PHP and "11" in JS. Java also gives "11" — its + concatenates whenever a String operand is involved — so all three "help" you, in three different ways. Python refuses:
>>> "1" + 1
TypeError: can only concatenate str (not "int") to strRun it yourself — it's one of the most common first errors:
>>> "1" + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
>>> int("1") + 1
2Python's philosophy: explicit conversion, implicit nothing. Convert with int(), str(), float(), bool(), list(), dict() — the same names as the types. Where other languages "help" by coercing, Python makes you say what you mean, which is why Python code tends to have fewer "it worked until the API returned a string" bugs.
1.6 The version landscape (as of November 2026)#
Versions move; check the official pages before assuming:
| Language | Current stable | Also supported | Source |
|---|---|---|---|
| Python | 3.15.x (3.15.0 released 9 Oct 2026) | 3.11–3.14 (3.10 went end-of-life Oct 2026) | python.org/downloads |
| PHP | 8.5.x (8.5.0 released 20 Nov 2025) | 8.3, 8.4; 8.2 security-only until Dec 2026; 8.6 in RC | php.net/supported-versions |
| JavaScript | Node.js 26 LTS "Lithium" (Oct 2026); browsers track the ECMAScript spec | Node 24, 22 LTS | nodejs.org |
| Java | JDK 27 (GA 15 Sep 2026); JDK 25 is the current LTS | 21, 17, 11, 8 (various vendors) | openjdk.org |
Notable recent arrivals you'll meet in docs and blogs: PHP 8.5 added the pipe operator |> and a (void) cast; Python 3.14 added template strings (t-strings) and better error messages, and 3.15 made UTF-8 the default encoding and added explicit lazy import, a built-in frozendict and a built-in sentinel type (all from the 3.15 What's New page, as of November 2026); Java shipped virtual threads (21) and pattern matching for switch (21). This path targets Python 3.11+ throughout — every sample runs on 3.11, 3.13 or 3.15.
Part 2: Types, truthiness and operators#
2.1 Numbers#
| Concept | PHP | JavaScript | Java | Python |
|---|---|---|---|---|
| Integer | int (64-bit) |
number (all numbers are doubles) + BigInt for big ones |
int, long, BigInteger |
int — arbitrary precision, never overflows |
| Decimal/float | float (IEEE-754 double) |
number |
double, float, BigDecimal |
float (IEEE-754 double); decimal.Decimal for money |
| True division | / → float, or int when evenly divisible (10 / 2 → int(5)); intdiv() for floor |
/ → number (may still print as 2.5) |
int/int → int (5/2 == 2); 5.0/2 → 2.5 |
/ → always float: 7/2 == 3.5 |
| Floor division | intdiv(7, 2) → 3 |
Math.floor(7/2) |
7 / 2 → 3 (integer division, truncates toward zero) |
7 // 2 → 3; -7 // 2 → -4 (floors) |
| Remainder | %, intdiv — sign of dividend |
% — sign of dividend |
% — sign of dividend |
% — sign of divisor: -7 % 2 == 1 |
| Overflow | wraps/errors by platform | number loses precision > 2⁵³; BigInt separate type |
long overflow wraps; BigInteger for exact |
never overflows; 10**30 is exact |
| Money | bcmul/gmp or int cents |
cents as number (risky) or a library |
BigDecimal |
decimal.Decimal or int cents |
Two behaviours deserve a demo because they differ from all three other languages:
print(-7 // 2, -7 % 2, divmod(-7, 2)) # -4 1 (-4, 1)
print(10**30 + 7) # 1000000000000000000000000000007 — exact
print(0.1 + 0.2 == 0.3) # False — same IEEE-754 as JS/Java doubles-4 1 (-4, 1)
1000000000000000000000000000007
False2.2 Strings and text#
Strings are immutable in Java, JavaScript and Python (str) — Java String, JS strings and Python str all refuse item assignment. PHP is the exception: its strings are byte arrays you can modify by offset ($s[0] = "H" works in PHP 8.x today; only the {} curly-brace form was removed in 8.0). The differences are in building and formatting them:
| Task | PHP | JavaScript | Java | Python |
|---|---|---|---|---|
| Interpolation | "Hi $name, you have {$n} msgs" |
`Hi ${name}, you have ${n} msgs` |
"Hi " + name or STR."..." (withdrawn — see note) or String.format/text blocks |
f"Hi {name}, you have {n} msgs" |
| Format spec | sprintf("%.2f", $x) |
`${x.toFixed(2)}` |
String.format("%.2f", x) |
f"{x:.2f}" |
| Concatenation | . operator |
+ |
+ |
+ (or better: "".join([...])) |
| Length | strlen (bytes!) |
.length (UTF-16 units!) |
.length() (UTF-16 units!) |
len(s) (code points) |
| Slice | substr/mb_substr |
.slice(a,b) / .substring |
.substring/.subSequence |
s[a:b], s[::-1] |
| Methods vs functions | functions: strtoupper($s), str_replace |
methods: s.toUpperCase(), s.replace |
methods: s.toUpperCase(), s.replace |
methods: s.upper(), s.replace |
| Multiline | heredoc <<<EOT |
template literal | text block """ |
triple-quoted """ or ''' |
The Python f-string is the closest thing to PHP interpolation or a JS template literal, and it is the idiom everywhere in this path:
name, price, qty = "USB-C hub", 1299.5, 3
print(f"{name}: {qty} x ${price:,.2f} = ${price * qty:,.2f}")
print(f"{qty = }, {price = }") # self-documenting since 3.8USB-C hub: 3 x $1,299.50 = $3,898.50
qty = 3, price = 1299.52.3 Booleans and truthiness — the full table#
| Language | Falsy values | Everything else |
|---|---|---|
| PHP | false, 0, 0.0, "", "0", [], null/unset |
truthy — including "0.00", "false", -1, NAN |
| JavaScript | false, 0, -0, 0n, "", null, undefined, NaN, document.all |
truthy — including [], {}, "0", "false" |
| Java | no truthiness — conditions require boolean/Boolean |
if (x) doesn't compile for non-booleans |
| Python | False, None, 0, 0.0, "", [], {}, (), set(), and any object whose __bool__/__len__ says so |
truthy |
Real Python output (run it — it's deterministic):
vals = [False, None, 0, 0.0, "", "0", [], {}, (), {1}, "false", "0.00"]
for v in vals:
print(f" {v!r:>10} -> {bool(v)}") False -> False
None -> False
0 -> False
0.0 -> False
'' -> False
'0' -> True
[] -> False
{} -> False
() -> False
{1} -> True
'false' -> True
'0.00' -> TrueThe cross-language traps, in order of how often they bite:
"0"is falsy in PHP, truthy in Python and JS. A PHP dev'sif ($s)guard ported toif s:lets"0"through.[]/{}are truthy in JS, falsy in Python and PHP.if (arr)in JS is always true — JS devs learn to writearr.length > 0; the Python habitif items:is what they wanted all along."false"and"0.00"are truthy strings in PHP (only""and"0"are falsy). Never test a string for emptiness by truthiness if it might contain"0"— compare explicitly.- Java has no implicit truthiness at all —
Optionalexists precisely becausenullchecks are verbose. Python'sx or defaultis the closest everyday equivalent, with the falsy caveat below.
2.4 Equality: ==, ===, .equals(), is#
| Language | Loose | Strict | Notes |
|---|---|---|---|
| PHP | == (juggles types!) |
=== (type + value) |
"1" == 1 → true; 0 == "foo" → false since PHP 8.0 (was true before — the famous bug) |
| JavaScript | == (coerces — avoid) |
=== / !== |
"1" === 1 → false; null == undefined → true but === false |
| Java | == on primitives; reference equality on objects |
.equals() (override per class) + Objects.equals(a,b) |
== on Integer caches −128..127 — Integer a=127,b=127; a==b is true, 128 is false! |
| Python | == calls __eq__ — value equality, no coercion |
is — identity (same object) |
"1" == 1 → false; [1] == [1] → true, [1] is [1] → false |
a = [1]
b = [1]
print(a == b, a is b) # True False
s1, s2 = "internee", "internee"
print(s1 == s2, s1 is s2) # True True — CPython interns; DO NOT rely on itTrue False
True TrueNone vs the field: Python has one missing value, None. PHP has null; JS has null and undefined (and NaN is its own weird value where NaN !== NaN); Java has null plus Optional<T>. In Python, None == False is False, None == 0 is False, but bool(None) is False — three different values that are all "falsy" (see 9.2).
2.5 The operators you know, and what replaces them#
| You write in… | PHP | JavaScript | Java | Python |
|---|---|---|---|---|
| Logical and/or/not | && || ! (also and/or/not with lower precedence — trap!) |
&& || ! |
&& || ! |
and or not — word operators only |
| Ternary | $x ? $a : $b |
cond ? a : b |
cond ? a : b |
a if cond else b |
| Null coalescing | ?? (PHP 7+) |
?? and ?. (ES2020) |
Optional.ofNullable(x).orElse(d) |
x or d (falsy!) or x if x is not None else d |
| Safe navigation | ?-> (PHP 8+) |
?. |
Optional.map(...) |
d.get("a", {}).get("b") — no ?. operator |
| Switch | match (8+) or switch |
switch |
switch expr (14+), patterns (21+) |
match/case (3.10+) |
| String contains | str_contains |
.includes |
.contains |
in: "x" in s |
| Spread/rest | ... (call unpacking 5.6+, array unpacking 7.4+, first-class callable (...) 8.1+) |
... |
varargs T... xs |
*args, **kwargs, *xs unpacking |
| Destructuring | [$a, $b] = $pair (7.1+), list() |
const [a, b] = arr |
none for locals (records have accessors) | a, b = pair — any iterable |
| Membership | in_array |
.includes / in |
.contains |
in for all containers |
| Exponent | ** |
** |
Math.pow |
**: 2**10 == 1024 |
| Increment | ++$i, $i++ |
++i, i++ |
++i, i++ |
does not exist — i += 1 |
Things to unlearn, concretely:
and/or/notare the only spellings.&&is a syntax error. They're also lower precedence than comparisons, which bites inif a == 1 and b == 2:— parenthesise when mixing.and/orreturn an operand, not a boolean."" or "fallback"→"fallback";"x" and "y"→"y". This is the engine behindx or defaultandx and y or zidioms — powerful, and a footgun when the operand is falsy-but-valid (0 or "anon"gives"anon", losing the real0). The safe null-check isx if x is not None else default.- No
++/--.i += 1is the idiom; augmented assignment (+=,-=,*=,//=,**=) exists. The trap for C-family developers:i++is aSyntaxError, but++iis valid Python — it parses as unary plus applied twice,+(+i), so it silently does nothing and your counter never moves. - Chained comparisons are a feature:
0 <= score <= 100works (Java/PHP need&&). match/case(3.10+) is structural pattern matching — closer to Java 21'sswitchpatterns or Rust'smatchthan to PHP'smatchexpression. It has no fall-through: once acasematches, its block runs and thematchends — nobreakneeded, unlike C-styleswitch(and unlike Java's old arrow-lessswitch, which still needsbreak). Full treatment in 01A.3.- Destructuring is just unpacking.
a, b = pairworks on any iterable — it's the PHP[$a, $b] = $pair/ JSconst [a, b] = arrhabit. Starred targets collect the rest:first, *rest = xs≈ JS[first, ...rest]. Swapping is the famous one-liner:a, b = b, a. - The walrus
:=(3.8+) lets you assign inside expressions:if m := re.search(p, s):— the JS/PHP equivalent of doing the check-then-use dance.
2.6 Missing values: None, null, undefined, NULL#
| "No value" | Unset variable | Missing dict key | Missing function arg | |
|---|---|---|---|---|
| PHP | null |
null + warning/E_WARNING |
warning + null |
ArgumentCountError (unless default) |
| JavaScript | null and undefined (distinct!) |
undefined (declared) / ReferenceError (undeclared let) |
undefined |
undefined |
| Java | null (+ Optional<T>) |
compile error | null (or Map.get → null) |
compile error / overloads |
| Python | None |
NameError at runtime |
KeyError at runtime |
TypeError at runtime |
The Python habit: check is None explicitly, get missing keys with .get() or in, and let NameError/KeyError/TypeError tell you about real bugs instead of papering over them with defaults everywhere. Optional[T] / T | None in type hints (01A.10) means "T or None" — the X | None spelling is the modern 3.10+ idiom.
2.7 Dates, times and time zones#
Timestamps are everywhere in AI work: request logs, cache expiry, "as of" dates in prompts, rate-limit windows. All four languages model them differently, and the bugs are always about time zones.
| PHP | JavaScript | Java | Python | |
|---|---|---|---|---|
| Main type | DateTimeImmutable (prefer it) / DateTime |
Date (a UTC millisecond timestamp, displayed in local time) |
java.time: Instant, ZonedDateTime, LocalDateTime |
datetime.datetime (naive or aware) |
| "No zone" type | DateTime with the default zone |
none — a Date always has an instant |
LocalDateTime |
a naive datetime (no tzinfo) |
| Month numbering | 1–12 | 0–11 (new Date(2026, 10, 6) is November) |
1–12 | 1–12 |
| Current time in UTC | new DateTimeImmutable("now", new DateTimeZone("UTC")) |
new Date() / Date.now() |
Instant.now() |
datetime.now(UTC) (from datetime import UTC, 3.11+) |
| ISO 8601 out | ->format(DATE_ATOM) |
d.toISOString() |
instant.toString() |
dt.isoformat() |
| ISO 8601 in | new DateTimeImmutable($s) |
new Date(s) / Date.parse |
Instant.parse(s) |
datetime.fromisoformat(s) |
| Add 30 days | $d->modify("+30 days") |
d.setDate(d.getDate() + 30) (mutates!) |
zdt.plusDays(30) |
dt + timedelta(days=30) |
| Zone database | built in | Intl / toLocaleString |
ZoneId |
zoneinfo.ZoneInfo("Europe/Paris") (stdlib, 3.9+) |
The Python rule that avoids most pain: store and compute in aware UTC; convert to a local zone only for display. A naive datetime is the same trap as Java's LocalDateTime — it looks like a time but names no instant — and Python refuses to compare naive with aware values, which is a feature:
from datetime import UTC, datetime, timedelta
aware = datetime(2026, 11, 6, 9, 30, tzinfo=UTC)
naive = datetime(2026, 11, 6, 9, 30)
print(aware.isoformat())
print(naive.isoformat())
print(aware + timedelta(days=30))
print(datetime.fromisoformat("2026-11-06T09:30:00+00:00") == aware)
try:
print(aware < naive)
except TypeError as e:
print("TypeError:", e)
print(aware.strftime("%d %b %Y, %H:%M"))2026-11-06T09:30:00+00:00
2026-11-06T09:30:00
2026-12-06 09:30:00+00:00
True
TypeError: can't compare offset-naive and offset-aware datetimes
06 Nov 2026, 09:30Part 3: Collections#
3.1 The collection map#
The biggest structural difference: PHP has one structure that is three things at once, JavaScript has objects plus arrays plus Map/Set, Java has a whole java.util hierarchy — and Python has four builtins, each with a clear job.
| Concept | PHP | JavaScript | Java | Python |
|---|---|---|---|---|
| Ordered list | array (also a map!) |
Array |
List (ArrayList, LinkedList) |
list |
| Fixed-size sequence | array |
typed arrays Int32Array |
int[], T[] |
tuple |
| Key→value map | array with string keys |
plain {} object; Map for non-string keys |
Map (HashMap, LinkedHashMap, TreeMap) |
dict |
| Unique set | no builtin (use array keys as a set) | Set |
Set (HashSet, TreeSet) |
set / frozenset |
| FIFO queue | SplQueue / array+array_shift |
Array + shift() |
ArrayDeque, LinkedList |
collections.deque |
| Ordered map | array (insertion order kept) |
Map (insertion-ordered) |
LinkedHashMap |
dict (insertion-ordered, guaranteed 3.7+) |
PHP's array is the famous oddity: array(1,2,3) and array("a"=>1,"b"=>2) are the same type — an ordered map. Every PHP "list" is secretly a map, which is why array_map preserves keys weirdly and why $arr[0] and $arr["0"] collide. Python splits the jobs cleanly.
3.2 Lists and arrays#
| Task | PHP | JavaScript | Java | Python |
|---|---|---|---|---|
| Literal | [1, 2, 3] or array(1,2,3) |
[1, 2, 3] |
List.of(1,2,3) / new int[]{1,2,3} |
[1, 2, 3] |
| Index | $a[0]; missing → warning + null |
a[0]; missing → undefined |
a.get(0) — throws IndexOutOfBoundsException |
a[0]; missing → IndexError |
| Slice | array_slice($a, 1, 2) |
a.slice(1, 3) |
a.subList(1,3) |
a[1:3] — and a[::-1] reverses |
| Append | $a[] = x |
a.push(x) |
a.add(x) |
a.append(x) |
| Remove last | array_pop($a) |
a.pop() |
a.remove(a.size()-1) |
a.pop() |
| Length | count($a) |
a.length |
a.size() |
len(a) |
| Iterate | foreach ($a as $v) / as $k => $v |
for (const v of a) / for...in (keys — trap) |
for (T v : a) |
for v in a: |
| Immutable? | copy-on-write | mutable | depends (List.of immutable) |
mutable (list); tuple immutable |
The Python surprises here:
list.sort()returnsNone;sorted()returns a new list. The Javalist.sort(c)habit — calling.sort()and using the result — silently yieldsNone:
tickets = [{"id": 1, "priority": 2}, {"id": 2, "priority": 1}, {"id": 3, "priority": 2}]
r = tickets.sort(key=lambda t: t["priority"])
print("sort() returned:", r)
print([(t["id"], t["priority"]) for t in tickets])sort() returned: None
[(2, 1), (1, 2), (3, 2)]+=on a list mutates in place;+creates a new list. This is the aliasing trap that bites everyone once:
x = [1]
y = x
x += [2]
print("+= :", x, y) # [1, 2] [1, 2] — same object!
x = [1]
y = x
x = x + [2]
print("+ :", x, y) # [1, 2] [1] — y kept the old list+= : [1, 2] [1, 2]
+ : [1, 2] [1]- Slicing copies.
a[1:3]anda[:]produce new lists;a[::2]every second;a[::-1]reversed. Strings slice the same way. There is nosubstr— negative indices count from the end (a[-1]is last).
3.3 Dictionaries, objects and maps#
| Task | PHP | JavaScript | Java | Python |
|---|---|---|---|---|
| Literal | ["a" => 1, "b" => 2] |
{a: 1, b: 2} |
Map.of("a",1,"b",2) |
{"a": 1, "b": 2} |
| Access | $m["a"] → warning+null |
m.a or m["a"] → undefined |
m.get("a") → null |
m["a"] → KeyError; m.get("a") → None |
| Safe access | $m["a"] ?? "d" |
m?.a ?? "d" |
m.getOrDefault("a","d") |
m.get("a", "d") |
| Add/update | $m["a"] = 1 |
m.a = 1 |
m.put("a",1) |
m["a"] = 1 |
| Keys iterate | foreach ($m as $k=>$v) |
Object.keys(m) / for k in m |
m.keySet() / entrySet() |
for k in m: (keys), m.items() |
| Merge | array_merge / + |
{...a, ...b} |
Map.putAll |
d1 | d2 (3.9+), d1.update(d2) |
| Order | insertion order (PHP 7+) | Map ordered; plain objects: string keys insertion, int keys sorted! |
LinkedHashMap ordered, HashMap not |
insertion order guaranteed (3.7+) |
| JSON round-trip | json_decode(..., true) |
JSON.parse |
Jackson/Gson | json.loads → dict |
The single most important fact for AI work: JSON objects decode to Python dicts, JSON arrays to lists, and the whole message/tool-call payload you will handle in Modules 03+ is nested dict/list/str/int/float/bool/None.
d = {"status": "open", "priority": "high", "id": 7}
print(list(d)) # ['status', 'priority', 'id'] — insertion order
print(d.get("missing")) # None — no exception
try:
d["missing"]
except KeyError as e:
print(f"KeyError: {e}") # KeyError: 'missing'
print(d.get("missing", "n/a")) # 'n/a'['status', 'priority', 'id']
None
KeyError: 'missing'
n/a3.4 Sets#
| Task | PHP | JavaScript | Java | Python |
|---|---|---|---|---|
| Literal | no builtin | new Set([1,2]) |
Set.of(1,2) / new HashSet |
{1, 2} |
| Add | $set[$v] = true trick |
s.add(v) |
s.add(v) |
s.add(v) |
| Contains | isset($set[$v]) |
s.has(v) |
s.contains(v) |
v in s — O(1), like a hash map |
| Union/intersect | array_intersect/array_merge+array_unique |
new Set([...a,...b]) |
s1.addAll(s2) etc. |
a | b, a & b, a - b, a ^ b |
| Order | keys keep insertion order | insertion order | HashSet unordered; LinkedHashSet ordered |
unordered — sort if you need order |
tags = ["bug", "ui", "bug", "api", "ui", "bug"]
print(sorted(set(tags))) # ['api', 'bug', 'ui'] — deduped, sorted
print(list(dict.fromkeys(tags))) # ['bug', 'ui', 'api'] — deduped, ORDER KEPT['api', 'bug', 'ui']
['bug', 'ui', 'api']3.5 Sorting: comparators vs key=#
| PHP | JavaScript | Java | Python | |
|---|---|---|---|---|
| Sort in place | sort($a) (reindexes!) / uasort |
a.sort(cmp) — in place, stable since ES2019 |
list.sort(cmp) — in place, stable List.sort/TimSort |
a.sort(key=..., reverse=...) — in place, returns None |
| New sorted list | rsort variants |
[...a].sort() / a.toSorted() (ES2023) |
stream().sorted() |
sorted(a, key=...) |
| Comparator | fn($a,$b) => $a <=> $b |
(a,b) => a-b |
(a,b) -> Integer.compare(...) |
key=lambda t: t["priority"] |
| Stability | all PHP sorts unstable before 8.0, stable since 8.0 | stable (ES2019+) | List.sort/Arrays.sort on objects stable |
stable, guaranteed |
The Python idiom is key=, a function applied to each element once — not a pairwise comparator. Multi-key sorts use a tuple: sorted(xs, key=lambda t: (t["priority"], -t["score"])). min/max take key= too. Going deeper: functools.cmp_to_key exists if you truly need a comparator.
3.6 Functional transforms vs comprehensions#
| Task | PHP | JavaScript | Java | Python |
|---|---|---|---|---|
| Map | array_map($f, $a) |
a.map(f) |
a.stream().map(f).toList() |
[f(x) for x in a] or list(map(f, a)) |
| Filter | array_filter($a, $p) |
a.filter(p) |
.filter(p) |
[x for x in a if p(x)] |
| Reduce | array_reduce($a, $f, $init) |
a.reduce(f, init) |
.reduce(...) |
sum(...), functools.reduce, or a loop |
| Any/all | in_array loop |
a.some(p) / a.every(p) |
.anyMatch/.allMatch |
any(p(x) for x in a) / all(...) — generator, lazy |
The Python idiom is the comprehension — it reads top-to-bottom like the JS chain but evaluates eagerly into a list (or lazily as a generator expression if you drop the brackets). [f(x) for x in a if p(x)] combines map+filter in one pass. Full treatment in 01A.5; the rule of thumb for switchers: comprehension for transforms, for loop when there's more than one statement inside.
3.7 Copying and mutability#
This is where PHP/JS/Java habits actively mislead:
| Operation | PHP | JavaScript | Java | Python |
|---|---|---|---|---|
| Assign | copy-on-write (looks like copy) | reference copy — b = a aliases |
reference copy — b = a aliases |
name rebinding — b = a aliases the object |
| Shallow copy | array copy on write |
[...a] / a.slice() / {...o} |
new ArrayList<>(a) |
a.copy(), list(a), a[:] |
| Deep copy | manual/unserialize(serialize) |
structuredClone(a) |
serialization/manual | copy.deepcopy(a) |
| Immutable option | none builtin | Object.freeze (shallow) |
List.of, Map.of |
tuple, frozenset, str, bytes, frozen dataclass |
import copy
a = [1, 2]
b = a
b.append(3)
print("alias :", a, b) # [1, 2, 3] [1, 2, 3] — same object
c = a.copy()
c.append(4)
print("copy() :", a, c) # [1, 2, 3] [1, 2, 3, 4]
nested = [[1], [2]]
shallow = nested.copy()
shallow[0].append(99)
print("shallow:", nested, shallow) # [[1, 99], [2]] [[1, 99], [2]] — inner list shared!
deep = copy.deepcopy(nested)
deep[0].append(100)
print("deep :", nested, deep) # nested unchanged by deep's appendalias : [1, 2, 3] [1, 2, 3]
copy() : [1, 2, 3] [1, 2, 3, 4]
shallow: [[1, 99], [2]] [[1, 99], [2]]
deep : [[1, 99], [2]] [[1, 99, 100], [2]]3.8 Iteration#
| Pattern | PHP | JavaScript | Java | Python |
|---|---|---|---|---|
| For each value | foreach ($a as $v) |
for (const v of a) |
for (T v : a) |
for v in a: |
| With index | foreach ($a as $i => $v) |
a.entries() / a.forEach((v,i)=>) |
indexed loop / IntStream |
for i, v in enumerate(a): |
| Parallel lists | array_map(null, $a, $b) |
zip via iterator/manual | indexed loop | for a, b in zip(xs, ys): |
| Iterate dict | foreach ($m as $k => $v) |
Object.entries(m) |
m.forEach((k,v)->) |
for k, v in m.items(): |
| Iterate lines of file | foreach (file($f) as $l) |
readline loop | Files.lines(p) |
for line in open(p): — file is iterable |
| Reverse | array_reverse |
[...a].reverse() / .toReversed() |
Collections.reverse / descendingIterator |
reversed(a) or a[::-1] |
The Python for loop works on any iterable — lists, tuples, dicts (keys), sets, strings (characters), files (lines), ranges, and anything with __iter__. This is the same protocol JS's for...of and Java's enhanced-for use, and it's why chunked HTTP reads work: httpx response objects are iterables, so for chunk in response.iter_bytes() (or iter_lines() for line-oriented bodies) plugs straight into a for loop — 03.3 iterates r.iter_bytes() into its SSE parser.
for i, n in enumerate([10, 20, 30], start=1):
print(i, n, end="; ")
print()
print(list(zip(["a", "b"], [1, 2])))1 10; 2 20; 3 30;
[('a', 1), ('b', 2)]Part 4: Functions and object-oriented programming#
4.1 Defining and calling functions#
| Concept | PHP | JavaScript | Java | Python |
|---|---|---|---|---|
| Define | function f($a, $b = 1) { ... } |
function f(a, b = 1) { ... } / const f = (a,b=1) => ... |
static int f(int a, int b) |
def f(a, b=1): |
| Return | return $x; (or implicit null) |
return x; |
return x; |
return x (implicit None) |
| Default args | $b = 1 |
b = 1 |
none — overloads or builders | b=1 — evaluated once at def time (see 9.1) |
| Keyword call | f(b: 2, a: 1) (named args, PHP 8+) |
f({a:1, b:2}) object or positional |
no named args | f(b=2, a=1) — the norm |
| Varargs | ...$args / func_get_args |
...args |
T... xs |
*args / **kwargs |
| Overloading | no (union types instead) | no | yes, compile-time | no — defaults, *args, or functools.singledispatch |
| Type enforcement | coercive/strict_types | none (JSDoc/TS) | compile-time | none at runtime — hints only |
def connect(host, port=443, **options):
return {"host": host, "port": port, "options": options}
print(connect("api.example.com", timeout=5, retries=3)){'host': 'api.example.com', 'port': 443, 'options': {'timeout': 5, 'retries': 3}}Rules of thumb translating habits:
selfis explicit. Methods aredef method(self, ...)insideclass; you writeself.xfor attributes andself.method(). There is no$thisinjection magic —selfis just the conventional first parameter name.- Keyword arguments are first-class, not an afterthought:
greet("Ada", punct="?"), and callers can reorder freely. This is why Python APIs (and every LLM SDK you'll use) are heavily keyword-driven. - No function overloading.
def f(x)anddef f(x, y)can't coexist — the seconddefreplaces the first. Use defaults,*args, orOptionalparameters instead. (Java's overloads map to defaults; Java's generics map to type hints, loosely.) *args/**kwargsunpack at call sites too:f(*list_of_args, **dict_of_kwargs)— the spread operator's real form.- Return type is optional and unenforced.
-> intis a hint for readers and type checkers, not a contract the runtime checks (that's Pydantic's job, 01B.6).
4.2 Closures and first-class functions#
Functions are objects: you can assign them, pass them, return them, store them in lists and dicts. lambda makes tiny anonymous ones; def is for anything multi-line.
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs]) # [2, 2, 2] — i is looked up at CALL time!
funcs2 = [lambda i=i: i for i in range(3)]
print([f() for f in funcs2]) # [0, 1, 2] — default arg binds early[2, 2, 2]
[0, 1, 2]| Concept | PHP | JavaScript | Java | Python |
|---|---|---|---|---|
| Anonymous fn | fn($x) => $x*2 (7.4+) |
x => x*2 / function(x){} |
x -> x*2 / (x) -> {} |
lambda x: x*2 |
| Named fn value | $f = 'strtoupper'; $f($s) |
const f = s => s.toUpperCase() |
Function<String,String> f = String::toUpperCase |
f = str.upper |
| Partial application | Closure::fromCallable/use |
.bind() |
method refs | functools.partial(f, 1) |
| Decorator | none builtin | none builtin | annotations (different!) | @decorator — a function wrapping a function |
4.3 Classes and objects#
| Concept | PHP | JavaScript | Java | Python |
|---|---|---|---|---|
| Declare | class Ticket { ... } |
class Ticket { ... } |
class Ticket { ... } |
class Ticket: |
| Constructor | __construct(...) |
constructor(...) |
Ticket(...) (same name as class) |
__init__(self, ...) — an initializer, not the constructor |
| Instantiate | new Ticket(...) |
new Ticket(...) |
new Ticket(...) |
Ticket(...) — no new |
| This/self | $this->x |
this.x |
this.x |
self.x (explicit param) |
| Inheritance | extends |
extends |
extends (single) / implements |
class B(A): + super() |
| Interface | interface |
none (duck typing / TS interfaces) | interface + implements |
Protocol (structural) or abc.ABC |
| Trait | trait + use |
mixins (unofficial) | default methods | mixin classes (rarely needed) |
| Visibility | public/protected/private |
#field private, _x convention |
public/protected/private/package |
convention only: _x "internal", __x name-mangled |
| Static member | static $x, static function |
static x, static m() |
static |
@staticmethod, @classmethod |
| Abstract | abstract class/abstract function |
n/a | abstract |
abc.ABC + @abstractmethod |
| Final | final class/final function |
n/a | final |
convention (_-prefix) or metaclass tricks — rarely used |
A minimal class, run for real:
class Ticket:
def __init__(self, tid, subject, priority=3):
self.id = tid
self.subject = subject
self.priority = priority
def __repr__(self):
return f"Ticket({self.id}, {self.subject!r}, p{self.priority})"
@property
def label(self):
return f"#{self.id}: {self.subject}"
t = Ticket(7, "Login fails", priority=1)
print(t) # Ticket(7, 'Login fails', p1)
print(t.label) # #7: Login fails
print(isinstance(t, Ticket), type(t).__name__) # True TicketTicket(7, 'Login fails', p1)
#7: Login fails
True Ticket4.4 Interfaces, traits and Protocol#
| You want | PHP | JavaScript | Java | Python |
|---|---|---|---|---|
| Contract only | interface |
TS interface (compile-time) |
interface |
typing.Protocol — structural: no implements needed |
| Abstract base | abstract class |
n/a | abstract class |
abc.ABC + @abstractmethod |
| Shared behaviour | trait |
mixin object/Object.assign |
default methods |
plain functions or mixin classes |
| Duck typing | PHP is dynamic — just call it | JS is dynamic — just call it | Java needs the type | Python: just call it (hasattr/try) or declare a Protocol for static checkers |
from typing import Protocol
class TicketClassifier(Protocol):
def classify(self, text: str) -> str: ...
def route(c: TicketClassifier, text: str) -> str:
return c.classify(text) # works for ANY object with .classify(text)->strProtocol is Python's structural typing: "if it has the method, it satisfies the contract" — like TypeScript's structural interfaces or Go interfaces, without an implements clause. abc.ABC is the nominal version (explicit subclassing required) for when you want runtime enforcement. Full depth in 01A.6.
4.5 Properties, getters and setters#
| PHP | JavaScript | Java | Python | |
|---|---|---|---|---|
| Getter | getName() or __get |
get name() |
getName() (or record accessor name()) |
@property def name(self) — accessed as obj.name, no () |
| Setter | setName($v) |
set name(v) |
setName(v) |
@name.setter |
| Computed | method | getter | method | @property — computed attribute that looks like data |
| Public field | $this->x |
this.x |
this.x (public) |
self.x — just an attribute |
Python's @property means call sites never change when you later add validation or computation — the JavaBeans getX()/setX() ceremony collapses to attribute syntax. Records/dataclasses (below) generate the boilerplate for you.
4.6 Constructors, statics and factories#
- Construction:
Ticket(7, "x")— nonew. Class-level factory:@classmethod def from_dict(cls, d)is the idiom (like Java's static factory methods or PHP's named constructors). - Static:
@staticmethod= Javastatic/PHPstatic/JSstatic— noself/this.@classmethodreceivescls(the class, for factories and alternative constructors). - Singleton: possible but rare; Python prefers module-level instances or DI. Don't cargo-cult Java singletons.
4.7 Enums, records and dataclasses#
| Concept | PHP | JavaScript | Java | Python |
|---|---|---|---|---|
| Enum | enum Status: string { case Open = 'open'; } (8.1+) |
no builtin (union of literals in TS) | enum Status { OPEN, CLOSED } |
Enum/StrEnum/IntEnum (3.11 has StrEnum) |
| Value object / record | no builtin | object literal | record Point(int x, int y) (16+) |
@dataclass or NamedTuple |
| Immutable data | readonly props (8.1+) | Object.freeze |
record | @dataclass(frozen=True) |
| Boilerplate | manual | manual | record generates | @dataclass generates __init__/__repr__/__eq__ |
from dataclasses import dataclass
from enum import StrEnum
class Status(StrEnum):
OPEN = "open"
CLOSED = "closed"
@dataclass(frozen=True)
class Ticket:
id: int
subject: str
status: Status = Status.OPEN
t = Ticket(1, "Login fails")
print(t) # Ticket(id=1, subject='Login fails', status=<Status.OPEN: 'open'>)
print(t.status == "open") # True — StrEnum compares equal to its valueTicket(id=1, subject='Login fails', status=<Status.OPEN: 'open'>)
True4.8 Generics, overloading and magic methods#
| Concept | PHP | JavaScript | Java | Python |
|---|---|---|---|---|
| Generics | no (docblock @template) |
TS generics <T> |
<T> + wildcards, erasure |
type hints: list[int], def f[T](x: T) -> T (3.12+ type params; older TypeVar) |
| Overloading | union types | union types (TS) | compile-time overloads | none — defaults/singledispatch |
| Magic/dunder | __get, __call, __toString |
Symbol.toPrimitive, getters |
toString, equals, hashCode, compareTo |
__repr__, __str__, __eq__, __len__, __iter__, __getitem__, __call__, __enter__/__exit__ |
| String repr | (string)$o / __toString |
String(o) / template |
o.toString() |
str(o) → __str__; repr(o) → __repr__ (debug form) |
| Callable object | __invoke |
function itself | lambda/Function |
__call__ on a class |
4.9 Modules, namespaces and imports#
| Concept | PHP | JavaScript | Java | Python |
|---|---|---|---|---|
| Unit of reuse | file + namespace |
file (ESM) or package | .java file / package |
module = one .py file; package = folder + __init__.py |
| Import | use Foo\Bar; / require |
import {x} from "./m.js" |
import com.foo.Bar; |
import module, from module import name, as |
| Autoload | Composer PSR-4 | bundler/node resolution | classpath | sys.path search; PYTHONPATH; installed packages |
| Manifest | composer.json |
package.json |
pom.xml/build.gradle |
pyproject.toml |
| Circular dep | possible, breaks | ESM handles some | compile handles | ImportError/partial-init — fix by restructuring |
Python's "namespace" is just the dotted module path (json.decoder); there's no namespace keyword and no visibility on imports — everything importable is public unless _-prefixed. if __name__ == "__main__": guards script-only code (the require.main === module / if __name__ equivalent). Deep dive in 01A.7.
Part 5: Errors and resource handling#
5.1 Four exception models#
| PHP | JavaScript | Java | Python | |
|---|---|---|---|---|
| Throw | throw new Exception(...) (any Throwable) |
throw anything (even strings!) |
throw new X(...) |
raise X(...) |
| Catch | try {} catch (E $e) {} finally {} |
try {} catch(e) {} finally {} |
try {} catch (E e) {} finally {} |
try: / except E as e: / else: / finally: |
| Checked? | no | no | yes — throws clause forces handling |
no — all unchecked |
| Hierarchy | Throwable → Exception/Error |
everything is an Error or any value |
Throwable → Exception/Error; RuntimeException unchecked |
BaseException → Exception → ValueError, TypeError, KeyError, IndexError, FileNotFoundError, RuntimeError... |
| Finally-equiv | finally |
finally |
finally, try-with-resources try (R r = ...) |
finally, or with (context manager) |
| Chaining | $e->getPrevious() |
cause property |
initCause/suppressed |
raise X from e |
5.2 try/except/else/finally, raise, raise ... from#
def parse_count(text):
try:
return int(text)
except ValueError as e:
raise RuntimeError(f"could not parse count from {text!r}") from e
try:
parse_count("12x")
except RuntimeError as e:
print(type(e).__name__, "-", e)
print("caused by:", type(e.__cause__).__name__, "-", e.__cause__)RuntimeError - could not parse count from '12x'
caused by: ValueError - invalid literal for int() with base 10: '12x'for raw in ["3", "nope"]:
try:
n = int(raw)
except ValueError:
print(f"{raw!r}: bad")
else:
print(f"{raw!r}: ok -> {n}")
finally:
print(" cleanup ran")'3': ok -> 3
cleanup ran
'nope': bad
cleanup ranThe mappings that matter:
except ValueError≈catch (NumberFormatException e)— catch the specific type, never bareexcept:(that'scatch (Throwable)and swallowsKeyboardInterrupt/SystemExittoo). Order matters:exceptclauses are tried top-down like Java's, so put subclasses first (except ParseErrorbeforeexcept TicketError— Python checksissubclass, demonstrated below).else:runs only if no exception — Java has no equivalent; it's where "happy path after the risky call" goes.finally:always runs — same as Java/JS/PHP. But preferwithfor resources (below).- Custom exceptions are just
class MyError(Exception): pass— a class hierarchy like Java's, but you define the root (AppError(Exception)) and branch on it.exceptmatches subclasses automatically:
class TicketError(Exception): pass
class ParseError(TicketError): pass
try:
raise ParseError("bad csv row 4")
except TicketError as e: # catches the subclass too
print("caught as TicketError:", e)caught as TicketError: bad csv row 4- EAFP vs LBYL: Python's idiom is "easier to ask forgiveness than permission" —
try: x = d[k] except KeyError:rather thanif k in d:. It's faster (no double lookup) and race-free. JS/PHP devs default toisset/hasOwnPropertychecks (LBYL); both work, EAFP is idiomatic.
5.3 Context managers: with#
with is Python's answer to Java's try-with-resources, PHP's finally, JS's using declarations and Rust's RAII — an object that cleans up on block exit, even on exception. (JS explicit resource management is a finished TC39 proposal with an expected publication year of 2027, per tc39/proposals' finished-proposals.md as of November 2026, so check your runtime's support before relying on using.)
import io
with io.StringIO("line1\nline2\n") as f:
data = f.read()
print(repr(data))
print("closed after with:", f.closed)'line1\nline2\n'
closed after with: TrueThe real uses you'll meet: with open(path) as f: (closes the file), with tempfile.TemporaryDirectory(), database connections, locks. contextlib.contextmanager lets you write your own with @contextmanager + yield. Covered fully in 01A.8 and 01A.9.
5.4 Error-handling design#
Same rules as everywhere, Python spelling: catch specific exceptions, don't swallow, let unexpected ones propagate, clean up in finally/with, and make messages actionable. The LLM-specific twist — provider errors are data, retries are bounded, validation failures feed back to the model — is 03.8 and 03.4; this module only gives you the try/except mechanics.
5.5 PHP's two error systems, and JS rejections vs exceptions#
Two traps hide inside the word "error" for switchers:
PHP has diagnostics and exceptions — try/catch only sees the second kind. E_WARNING, E_NOTICE, E_DEPRECATED and friends are not exceptions: they don't unwind the stack, catch can't see them, and the default behaviour is "log/print and carry on with a null or degraded result". You install set_error_handler() to escalate them into exceptions yourself. The throwable side is narrower than it looks: only Exception and Error implement Throwable, and catch (Exception $e) misses Error — catch Throwable when you mean both. PHP 8 raised the stakes: operations that used to emit a warning now throw TypeError, ValueError or DivisionByZeroError, so PHP 7-era code can fail harder on PHP 8/8.5, not softer.
| PHP mechanism | What it is | Python analogue |
|---|---|---|
E_WARNING / E_NOTICE / E_DEPRECATED |
diagnostic; no stack unwind; set_error_handler can escalate |
closest is warnings.warn / logging — not an exception |
Exception (RuntimeException, InvalidArgumentException…) |
catchable business error | Exception subclasses (ValueError, KeyError…) |
Error (TypeError, ValueError, DivisionByZeroError…) |
engine-level failure | TypeError, ZeroDivisionError — same names, same job |
JavaScript: a rejected Promise is not an exception — until someone awaits it. throw inside an async function (or a sync function) behaves like Python's raise at the point it's hit. But Promise.reject(e) — or a fetch that fails — produces a rejection that travels with the promise object; try/catch around the call never sees it. try/catch around the await does, because await re-throws the rejection at that point. A rejection nobody handles fires unhandledrejection; on modern Node (15+) the default is to crash the process — the moral equivalent of an exception escaping asyncio.run.
Python's model maps cleanly onto both: raise creates the exception immediately; inside a coroutine it propagates through the await expression exactly like a synchronous call, so try/except placement around await matters as much as around a blocking call; and an exception inside a task nobody awaits surfaces when the task is collected or the loop shuts down — analogous to an unhandled rejection.
import asyncio
async def failing():
await asyncio.sleep(0)
raise ValueError("provider said no")
async def main():
try:
await failing()
except ValueError as e:
print("caught at await:", e)
asyncio.run(main())caught at await: provider said nogather(..., return_exceptions=True) ≈ Promise.allSettled; plain gather fails fast on the first exception like Promise.all fails on the first rejection (Part 6).
Part 6: Async and concurrency (a preview)#
Deep-dive
6.1 The event loop#
| PHP | JavaScript (Node) | Java | Python | |
|---|---|---|---|---|
| Async primitive | Fibers (8.1+, cooperative) / ReactPHP, Amp | Promise + async/await |
CompletableFuture, virtual threads |
async def coroutine + await + asyncio loop |
| Concurrency model | one request per FPM process | single-threaded event loop | thread pools / virtual threads | event loop + optional threads |
| Run all, keep order | Amp\Future\await / React\Promise\all |
Promise.all([...]) / allSettled |
CompletableFuture.allOf(...) |
await asyncio.gather(...) |
| Blocking call inside async | blocks the worker | blocks the whole loop! | N/A (threads) | asyncio.to_thread(...) or run_in_executor |
import asyncio
async def fetch(label, delay):
await asyncio.sleep(delay)
return f"{label} done"
async def main():
results = await asyncio.gather(
fetch("tickets", 0.05), fetch("invoices", 0.01), fetch("users", 0.03),
)
print(results)
asyncio.run(main())['tickets done', 'invoices done', 'users done']asyncio.gather is Promise.all: start everything, results keep input order. return_exceptions=True ≈ Promise.allSettled. The difference to internalise: await only works inside async def, and the loop only runs under asyncio.run() — there's no top-level await in scripts (unlike JS modules).
6.2 Threads, processes and the GIL#
- PHP: PHP-FPM handles each request in its own process — "concurrency" is horizontal scaling, not threads. Fibers give cooperative multitasking inside one request.
- JavaScript: the event loop is single-threaded;
worker_threadsfor CPU work. - Java: real OS threads; virtual threads (21+) make
Thread.ofVirtual()cheap enough to use one per request. - Python: real threads exist (
threading,concurrent.futures) but the GIL means only one thread runs Python bytecode at a time — fine for I/O-bound waits (HTTP calls, file reads, which release the GIL), useless for CPU-bound parallelism (usemultiprocessingor NumPy's native code).asynciois the idiom for many concurrent I/O waits.
For LLM work — hundreds of concurrent HTTP calls — asyncio + bounded concurrency is the whole game; that's 01B.3 and 01B.4.
6.3 The mapping in one line#
Promise.all ↔ asyncio.gather · fetch/await ↔ httpx.AsyncClient/await (01B.5) · Promise.allSettled ↔ gather(return_exceptions=True) · CompletableFuture.allOf ↔ gather · PHP queue worker ↔ asyncio task or batch API.
Part 7: Tooling and ecosystem#
Deep-dive
7.1 Package managers and manifests#
| PHP | JavaScript | Java | Python | |
|---|---|---|---|---|
| Manifest | composer.json |
package.json |
pom.xml / build.gradle(.kts) |
pyproject.toml (PEP 621) |
| Install tool | composer require x |
npm install x / pnpm / yarn |
mvn / gradle |
uv add x / pip install x |
| Lockfile | composer.lock |
package-lock.json |
pom.xml versions / Gradle lockfile |
uv.lock / requirements.txt |
| Registry | Packagist | npm registry | Maven Central | PyPI |
| Autoload/install | PSR-4 autoload | node_modules |
classpath/jar | site-packages / editable install |
| Global vs local | composer global |
-g flag |
rarely global | always use a project env — see below |
7.2 Environments and dependency isolation#
- PHP: Composer installs into
vendor/per project; no built-in venv concept (each project has its ownvendor/). - JavaScript:
node_modules/per project (npm) or global store (pnpm);.nvmrc/engines pin Node. - Java: Maven/Gradle resolve into
~/.m2/~/.gradlecaches; no per-project isolation needed (JVM classpath). - Python:
venv/uvcreates an isolated environment per project — thenode_modulesequivalent, but it isolates the interpreter and packages, not just files. Neverpip installglobally; always inside a project oruv run. This is 01B.1.
uv init myproject --bare --python 3.13 # fresh project with pyproject.toml
cd myproject
uv add requests # resolves, locks, installs into .venv
uv add --dev pytest # dev tool — not shipped with the app
uv run python script.py # runs inside the project env
uv run pytest # dev tool, same env7.3 Linting, formatting and testing#
| Concern | PHP | JavaScript | Java | Python |
|---|---|---|---|---|
| Linter | PHPStan/Psalm, PHP-CS-Fixer | ESLint | Checkstyle/SpotBugs/Error Prone | ruff check |
| Formatter | PHP-CS-Fixer/Pint | Prettier | Spotless/google-java-format | ruff format |
| Test runner | PHPUnit | Jest/Vitest | JUnit 5 | pytest |
| Types (optional) | PHPDoc + PHPStan | TypeScript/JSDoc | javac generics | type hints + mypy/pyright/ty |
Python consolidated lint+format+import-sort into Ruff (one fast Rust tool) and testing into pytest — the equivalents of ESLint+Prettier+Jest. 01A.10 covers ruff; 01B.8 covers pytest.
7.4 Frameworks map (names only — not taught here)#
| Domain | PHP | JavaScript | Java | Python |
|---|---|---|---|---|
| Web API | Laravel, Symfony | Express, Fastify, Next.js | Spring Boot, Micronaut, Quarkus | FastAPI, Django, Flask |
| ORM | Eloquent/Doctrine | Prisma/TypeORM | JPA/Hibernate | SQLAlchemy, Django ORM |
| CLI | Symfony Console | commander/yargs | Picocli | argparse, typer, click |
| Async HTTP | Guzzle, ReactPHP | fetch/axios |
java.net.http, OkHttp |
httpx/httpx2 (01B.5) |
| Templating | Blade/Twig | JSX/EJS | Thymeleaf | Jinja2 |
7.5 Typing across the four languages#
| PHP | JavaScript | Java | Python | |
|---|---|---|---|---|
| Native types | yes (7+/8 union types) | none — JSDoc/TS | yes, generics | hints only — not enforced at runtime |
| Nullable | ?int |
number | null (TS) |
Integer/Optional |
int | None / Optional[int] |
| Generic container | docblock | Array<T> (TS) |
List<String> |
list[str] |
| Structural | no | TS structural | no (nominal) | Protocol |
| Runtime validation | no | no | no | Pydantic (01B.6) — hints → schema → validation |
The Python twist: def f(x: int) -> str is a promise to readers and tools, not a runtime check — f("not an int") still runs. If you need enforcement, that's Pydantic or manual checks. 01A.10 is the deep dive; 03.1 shows reading SDK signatures.
7.6 Running and deploying#
| PHP | JavaScript | Java | Python | |
|---|---|---|---|---|
| Run script | php script.php |
node script.js |
java Main / mvn exec |
python3 script.py / uv run |
| REPL | php -a / psysh |
node / bun |
jshell |
python3 (the REPL) / ipython |
| Bytecode/cache | OPcache | V8 compile cache | .class/JIT |
.pyc in __pycache__ |
| Deploy | php-fpm + nginx | node process / serverless | JVM jar/container | process / serverless / container |
| Config | .env + env() |
.env + process.env |
application.yml/env |
.env + os.environ/pydantic-settings (01B.2) |
Part 8: The idiom translation table#
Reference
Forty snippets you'll actually write. The Python column is what to reach for; the others show the habit it replaces. (Table cells are fragments — the runnable versions are in 01A.1–01A.10.)
| # | Task | PHP | JavaScript | Java | Python |
|---|---|---|---|---|---|
| 1 | Join strings | implode(", ", $a) |
a.join(", ") |
String.join(", ", a) |
", ".join(a) |
| 2 | Interpolate | "Hi $name" |
`Hi ${name}` |
"Hi " + name |
f"Hi {name}" |
| 3 | Map | array_map($f, $a) |
a.map(f) |
a.stream().map(f) |
[f(x) for x in a] |
| 4 | Filter | array_filter($a, $p) |
a.filter(p) |
.filter(p) |
[x for x in a if p(x)] |
| 5 | Sum/reduce | array_sum($a) |
a.reduce((s,x)=>s+x,0) |
.reduce(...) |
sum(a) |
| 6 | Key exists | isset($m["k"]) / array_key_exists |
"k" in m |
m.containsKey("k") |
"k" in m |
| 7 | Get + default | $m["k"] ?? "d" |
m.k ?? "d" |
m.getOrDefault("k","d") |
m.get("k", "d") |
| 8 | Safe nested get | $m["a"]["b"] ?? null |
m?.a?.b |
Optional chain |
m.get("a", {}).get("b") |
| 9 | Null → default | ?? |
?? |
Optional.orElse |
x if x is not None else d |
| 10 | Ternary | $c ? $a : $b |
c ? a : b |
c ? a : b |
a if c else b |
| 11 | Switch | match($x){...} (8+) |
switch(x) |
switch expr (14+) |
match x: / case |
| 12 | Read file | file_get_contents($p) |
fs.readFileSync(p,"utf8") |
Files.readString(p) |
Path(p).read_text(encoding="utf-8") |
| 13 | Write file | file_put_contents($p,$s) |
fs.writeFileSync(p,s) |
Files.writeString(p,s) |
Path(p).write_text(s, encoding="utf-8") |
| 14 | JSON decode | json_decode($s, true) |
JSON.parse(s) |
mapper.readValue(s, ...) |
json.loads(s) |
| 15 | JSON encode | json_encode($d) |
JSON.stringify(d) |
mapper.writeValueAsString(d) |
json.dumps(d) |
| 16 | HTTP GET | file_get_contents($url) / Guzzle |
fetch(url).then(r=>r.json()) |
HttpClient.send(...) |
httpx.get(url) (01B.5) |
| 17 | Format date | date("Y-m-d", $t) |
d.toISOString().slice(0,10) |
DateTimeFormatter |
d.strftime("%Y-%m-%d") |
| 18 | Sort by field | usort($a, fn($x,$y)=>$x["k"]<=>$y["k"]) |
a.sort((x,y)=>x.k-y.k) |
a.sort(Comparator.comparing(T::k)) |
sorted(a, key=lambda t: t["k"]) |
| 19 | Unique, keep order | array_values(array_unique($a)) |
[...new Set(a)] |
new LinkedHashSet<>(a) |
list(dict.fromkeys(a)) |
| 20 | Regex search | preg_match('/(\d+)/', $s, $m) |
s.match(/(\d+)/) |
Pattern.compile(...).matcher(s) |
re.search(r"(\d+)", s) → .group(1) |
| 21 | Regex replace | preg_replace('/\d+/', 'N', $s) |
s.replace(/\d+/g,'N') |
s.replaceAll("\\d+","N") |
re.sub(r"\d+","N",s) |
| 22 | Define class | class P { public function __construct(public int $x){} } |
class P { constructor(x){this.x=x} } |
record P(int x){} |
@dataclass class P: x: int |
| 23 | Contract/iface | interface I { public function f(); } |
TS interface I { f(): void } |
interface I { void f(); } |
class I(Protocol): def f(self): ... |
| 24 | str→int safe | (int)$s / filter_var |
parseInt(s) (NaN!) |
Integer.parseInt(s) throws |
int(s) raises ValueError |
| 25 | Env var | $_ENV["K"] ?? "d" |
process.env.K ?? "d" |
System.getenv().getOrDefault |
os.environ.get("K", "d") |
| 26 | CLI args | $argv |
process.argv |
args param |
sys.argv / argparse |
| 27 | Count items | count($a) / array_count_values |
a.length / reduce |
a.size() / Collectors |
len(a) / Counter(a) |
| 28 | Split string | explode(",", $s) |
s.split(",") |
s.split(",") |
s.split(",") |
| 29 | Trim | trim($s) |
s.trim() |
s.strip() |
s.strip() |
| 30 | Contains/prefix | str_contains/str_starts_with |
s.includes/startsWith |
s.contains/startsWith |
"x" in s / s.startswith |
| 31 | Reverse string | strrev($s) |
[...s].reverse().join("") |
new StringBuilder(s).reverse() |
s[::-1] |
| 32 | Index+value loop | foreach($a as $i=>$v) |
a.forEach((v,i)=>) / entries() |
indexed for |
for i, v in enumerate(a): |
| 33 | Zip two lists | array_map(null,$a,$b) |
manual/iterator | indexed for |
for x, y in zip(a, b): |
| 34 | First N | array_slice($a,0,$n) |
a.slice(0,n) |
a.subList(0,n) |
a[:n] |
| 35 | Flatten nested | array_merge(...$a) |
a.flat() |
a.stream().flatMap(...) |
[x for sub in a for x in sub] |
| 36 | Any / all | loop | a.some(p)/a.every(p) |
.anyMatch/.allMatch |
any(p(x) for x in a) / all(...) |
| 37 | Dict key+value | foreach($m as $k=>$v) |
Object.entries(m) |
m.forEach((k,v)->) |
for k, v in m.items(): |
| 38 | Main guard | if (realpath($_SERVER['SCRIPT_FILENAME'] ?? '') === __FILE__) |
require.main === module (CJS; ESM: compare import.meta.url to the entry path) |
n/a (JVM entry main) |
if __name__ == "__main__": |
| 39 | Random int | random_int(1,10) |
Math.floor(Math.random()*10)+1 |
ThreadLocalRandom.current().nextInt(1,11) |
random.randint(1,10) |
| 40 | Type check | is_int($x) / gettype |
typeof x === "number" |
x instanceof Integer |
isinstance(x, int) |
Part 9: Python surprises gallery#
Reference
Every entry below was run for real (Python 3.14.6; all outputs are stable across 3.11+).
9.1 Mutable default arguments#
def add_item(item, items=[]):
items.append(item)
return items
print(add_item("a")) # ['a']
print(add_item("b")) # ['a', 'b'] — the default list PERSISTS between calls!
print(add_item("c")) # ['a', 'b', 'c']['a']
['a', 'b']
['a', 'b', 'c']Default values are evaluated once at def time, so [] is one shared list forever. Fix: items=None then items = [] if items is None else items inside. This trap is Python-specific for a switcher: JavaScript evaluates a default-parameter expression on every call, so function f(a = []) gets a fresh array each time; PHP defaults are constant expressions or new initializers evaluated per call; Java has no default arguments at all. Don't assume the bug exists in the language you came from, and don't assume it's absent in Python.
9.2 None, False and 0 are different values#
print(None == False, None == 0) # False False
print(bool(None), bool(False), bool(0)) # False False False — all falsy, all distinctFalse False
False False FalsePHP's null == false is true — porting if (!$x) guards needs care: if x is None checks missing, if not x checks falsy (catches 0, "", [] too). Pick deliberately.
9.3 Names resolve at call time#
x = "global"
def show():
return x
print(show()) # global
x = "changed"
print(show()) # changed — functions see the CURRENT globalglobal
changedClosures capture variables, not values — same rule as 4.2. Module-level constants are read at call time; "constants" are convention, not enforcement.
9.4 for/else and the leaking loop variable#
for n in [1, 2, 3, 4]:
if n == 3:
break
else:
print("no break happened") # skipped — break ran
print("after the loop, n =", n) # n = 3 — loop vars outlive the loopafter the loop, n = 3for...else runs the else only when the loop didn't break — the "found it?" idiom. And n survives the loop because there's no block scope (1.4). Java's for (int i...) scoping doesn't exist; don't rely on i being undefined after.
9.5 Strings are immutable#
s = "hello"
try:
s[0] = "H"
except TypeError as e:
print("TypeError:", e)
s = "H" + s[1:]
print(s)TypeError: 'str' object does not support item assignment
HelloSame as Java String and JS strings. The "modify" idiom is s = s[:0] + "H" + s[1:] or better "H" + s[1:] — build a new string. (PHP strings are byte-mutable via $s[0] = "H" today — don't port that habit.)
9.6 // floors toward −∞; % has the divisor's sign#
print(-7 // 2, -7 % 2, divmod(-7, 2)) # -4 1 (-4, 1)-4 1 (-4, 1)Java/JS/PHP -7 % 2 is -1. Python's 1. Any ported hash/calendar/ring-buffer math with negatives needs checking. math.floor-style division is the consistent choice.
9.7 Comprehension variables have their own scope#
squares = [i * i for i in range(4)]
print(squares) # [0, 1, 4, 9]
try:
print(i)
except NameError as e:
print(f"NameError: {e}")[0, 1, 4, 9]
NameError: name 'i' is not defined[x for x in ...] doesn't leak x; for x in ...: does. The one place Python does have a hidden scope — and it surprises everyone.
9.8 Module-level code runs on import#
# p10_module_scope.py (top level)
VALUE = "computed at import"
print("p10_module_scope.py top level executed")
def get_value():
return VALUE# importer.py
import p10_module_scope as m
print("importer got:", m.get_value())
print("again:", m.get_value())p10_module_scope.py top level executed
importer got: computed at import
again: computed at importImporting a module executes its top level once (cached in sys.modules). Guard side effects behind if __name__ == "__main__": — the JS require.main === module equivalent. This is why "just importing" can print, connect, or be slow.
9.9 dict keeps insertion order; set doesn't#
print(list({"b": 1, "a": 2, "c": 3})) # ['b', 'a', 'c'] — insertion order
tags = ["bug", "ui", "bug", "api"]
print(list(dict.fromkeys(tags))) # ['bug', 'ui', 'api'] — order kept
print(sorted(set(tags))) # ['api', 'bug', 'ui'] — set loses order['b', 'a', 'c']
['bug', 'ui', 'api']
['api', 'bug', 'ui']Guaranteed since 3.7 — JSON objects round-trip preserving key order. set/frozenset are unordered: never iterate a set expecting order; use dict.fromkeys for ordered dedupe.
9.10 bool is an int subclass#
print(True + True) # 2
print(isinstance(True, int)) # True
print(True == 1, False == 0) # True True
print(True is 1) # False — equal, not identical2
True
True True
False(True is 1 also emits SyntaxWarning: "is" with 'int' literal on current Python.) True == 1 is True because bool subclasses int. Usually harmless, occasionally bizarre in arithmetic — don't use booleans as numbers.
9.11 is vs ==, and small-int caching#
a = [1]; b = [1]
print(a == b, a is b) # True False — equal values, different objects
x = 7; y = 7
print(x is y) # True — CPython caches small ints (-5..256)
z = 1000; w = 1000
print(z is w) # may be True or False — implementation detail!True False
True
Trueis compares identity (same object), == compares value. Small ints and some strings are interned so is can accidentally be True — never rely on it. x is None / x is True are the only everyday uses. (The z is w result is CPython-specific and can change; that's the point.)
9.12 += on lists mutates the alias#
x = [1]; y = x
x += [2]
print(x, y) # [1, 2] [1, 2] — same object, both changed
x = [1]; y = x
x = x + [2]
print(x, y) # [1, 2] [1] — new object, y kept the old list[1, 2] [1, 2]
[1, 2] [1]+= calls __iadd__ which extends in place; + builds a new list. Same trap as the 3.2 demo — the fix is x = x + [2] or x = [*x, 2] when you want a copy.
9.13 sort() returns None#
tickets = [{"id": 1, "p": 2}, {"id": 2, "p": 1}]
r = tickets.sort(key=lambda t: t["p"])
print(r) # None — sorted in place
print([t["id"] for t in tickets]) # [2, 1]None
[2, 1].sort() mutates and returns None (like Java's List.sort); sorted() returns a new list. list.sort(key=...) is stable — equal keys keep original order.
9.14 Shadowing builtins#
list = [1, 2, 3] # shadows the builtin list() constructor
print(list) # [1, 2, 3]
# print(list("ab")) # TypeError now — list is the variable, not the typeAssigning list, dict, str, id, type, input, next, sum, max shadows the builtin for the rest of the scope. Linters flag it; the fix is rename (items = ...) — it's legal but a classic "works until it doesn't" bug.
9.15 match has no fall-through#
status = "open"
match status:
case "open":
print("reopened")
case "closed":
print("archived")
case _:
print("other")reopenedA C-style switch (and Java's old colon-style switch) keeps executing every matching case until a break — forget the break and cases cascade. Python's match/case (3.10+) runs the first matching block and ends — no fall-through, no break needed, case _ is the default. Guards add conditions: case x if x > 10:. Details in 01A.3.
Part 10: The same program in four languages#
Reference
The task: read tickets.json, group by status, count priority within each group, print a summary. Same input, same logic, four spellings. The Python version runs for real (output below); the other three are illustrative translations — correct in shape, not executed here.
The shared input file — save this as tickets.json next to the scripts:
[
{"id": 1, "subject": "Login fails after SSO update", "status": "open", "priority": "high"},
{"id": 2, "subject": "Invoice PDF missing VAT line", "status": "open", "priority": "normal"},
{"id": 3, "subject": "Dashboard chart renders blank", "status": "in-progress", "priority": "high"},
{"id": 4, "subject": "Password reset email delayed", "status": "open", "priority": "low"},
{"id": 5, "subject": "Export to CSV truncates rows", "status": "open", "priority": "high"},
{"id": 6, "subject": "Mobile nav overlaps footer", "status": "closed", "priority": "low"},
{"id": 7, "subject": "Webhook retries forever", "status": "in-progress", "priority": "normal"},
{"id": 8, "subject": "Search ignores hyphens", "status": "closed", "priority": "normal"}
]Python (report.py, runs on stdlib only):
import json
from collections import Counter, defaultdict
from pathlib import Path
def summarise(path):
tickets = json.loads(Path(path).read_text(encoding="utf-8"))
by_status = defaultdict(list)
for t in tickets:
by_status[t["status"]].append(t)
print(f"{len(tickets)} tickets")
for status in sorted(by_status):
group = by_status[status]
priorities = Counter(t["priority"] for t in group)
print(f" {status}: {len(group)}")
for p in ("low", "normal", "high"):
if priorities[p]:
print(f" {p}: {priorities[p]}")
if __name__ == "__main__":
import sys
summarise(sys.argv[1] if len(sys.argv) > 1 else "tickets.json")8 tickets
closed: 2
low: 1
normal: 1
in-progress: 2
normal: 1
high: 1
open: 4
low: 1
normal: 1
high: 2PHP (illustrative — needs php, not run here):
<?php
$tickets = json_decode(file_get_contents($argv[1] ?? "tickets.json"), true);
$byStatus = [];
foreach ($tickets as $t) { $byStatus[$t["status"]][] = $t; }
ksort($byStatus);
echo count($tickets), " tickets\n";
foreach ($byStatus as $status => $group) {
$counts = array_count_values(array_column($group, "priority"));
echo " $status: ", count($group), "\n";
foreach (["low","normal","high"] as $p) {
if (!empty($counts[$p])) echo " $p: {$counts[$p]}\n";
}
}JavaScript (illustrative — needs Node, not run here):
const fs = require("fs");
const tickets = JSON.parse(fs.readFileSync(process.argv[2] ?? "tickets.json", "utf8"));
const byStatus = {};
for (const t of tickets) (byStatus[t.status] ??= []).push(t);
console.log(`${tickets.length} tickets`);
for (const status of Object.keys(byStatus).sort()) {
const group = byStatus[status];
const counts = {};
for (const t of group) counts[t.priority] = (counts[t.priority] ?? 0) + 1;
console.log(` ${status}: ${group.length}`);
for (const p of ["low", "normal", "high"])
if (counts[p]) console.log(` ${p}: ${counts[p]}`);
}Java (illustrative — needs JDK + Jackson, not run here):
import com.fasterxml.jackson.databind.ObjectMapper;
import java.nio.file.*;
import java.util.*;
record Ticket(int id, String subject, String status, String priority) {}
public class Report {
public static void main(String[] args) throws Exception {
var mapper = new ObjectMapper();
var tickets = mapper.readValue(
Files.readString(Path.of(args.length > 0 ? args[0] : "tickets.json")),
Ticket[].class);
var byStatus = new TreeMap<String, List<Ticket>>();
for (var t : tickets) byStatus.computeIfAbsent(t.status(), k -> new ArrayList<>()).add(t);
System.out.println(tickets.length + " tickets");
for (var e : byStatus.entrySet()) {
var counts = new TreeMap<String, Long>();
for (var t : e.getValue()) counts.merge(t.priority(), 1L, Long::sum);
System.out.println(" " + e.getKey() + ": " + e.getValue().size());
for (var p : List.of("low", "normal", "high"))
if (counts.containsKey(p)) System.out.println(" " + p + ": " + counts.get(p));
}
}
}What to notice: PHP's ??= and array_count_values do the grouping in library calls; JS's ??= and Object.keys().sort(); Java's computeIfAbsent/merge/TreeMap (sorted for free); Python's defaultdict + Counter — the same shape, shortest spelling. The Python version is ~20 lines; the Java one needs a JSON library because the JDK has none built in (a real difference worth knowing).
Part 11: The 30-minute fast track#
If you already know one of these languages cold, here's what to read and what to skip. Times assume ~2 minutes per table row skimmed.
Coming from PHP#
| Read properly | Skim | Skip (you know it) |
|---|---|---|
Part 1 (mindset, names-not-boxes, no $) |
Part 2 tables (you'll recognise most) | — |
Part 3 collections (dict vs PHP array, list vs array) |
Part 4 OOP (self, __init__, @property) |
— |
Part 5 errors (try/except, with) |
Part 6 async preview | — |
| Part 8 idiom table (the PHP column) | Part 7 tooling | PHP-specific syntax |
Part 9 surprises — mutable defaults, += aliasing, ///% sign, is vs == |
Part 10 (compare PHP vs Python sides) | — |
| Part 11 (you're here) |
Gotchas to not skip: mutable default args, += vs + on lists, ///% floor semantics, is vs ==, no block scope, None vs False/0, module-level code on import.
Coming from JavaScript / TypeScript#
| Read properly | Skim | Skip |
|---|---|---|
| Part 1 (names-not-boxes is new; you know dynamic typing) | Part 2 (truthiness differs: []/{} falsy in Python) |
var/let/const — Python has none |
Part 3 collections (dict insertion order, list vs array) |
Part 4 OOP (classes are familiar; __init__, @property, Protocol are new) |
— |
| Part 5 errors | Part 6 async (asyncio.gather ≈ Promise.all — you know this) |
— |
| Part 8 idiom table (JS column) | Part 7 tooling | Promise/await syntax — mostly same |
Part 9 surprises — mutable defaults, late binding, sort() returns None, += aliasing |
Part 10 | — |
| Part 11 |
Gotchas: []/{} are falsy in Python (truthy in JS!), "0" is truthy (falsy in PHP but truthy in JS too), for...in traps don't exist but loop vars leak, dict preserves order (JS objects don't for int keys), no ?./?? operators (use .get()/or).
Coming from Java#
| Read properly | Skim | Skip |
|---|---|---|
Part 1 (dynamic typing, names-not-boxes, no new, no checked exceptions) |
Part 2 (you know static typing; Python hints are weaker) | Generics syntax — hints differ |
Part 3 collections (list/dict/set vs List/Map/Set, slicing, key= sort) |
Part 4 OOP (self explicit, __init__, Protocol, dataclasses ≈ records) |
interface/implements — Protocol is structural |
Part 5 errors (no checked exceptions, with ≈ try-with-resources) |
Part 6 async (threads vs asyncio/GIL — genuinely different) |
— |
| Part 8 idiom table (Java column) | Part 7 tooling | Streams — comprehensions replace most |
Part 9 surprises — mutable defaults, += aliasing, truthiness (Java has none!), for/else, None vs null |
Part 10 | — |
| Part 11 |
Gotchas: no new, no checked exceptions, no final/private enforcement (convention), bool is int, truthiness exists (unlike Java), ///% sign differs from Java's %, list.sort() returns None, mutable default args, loop vars leak, no block scope.
Then continue to Module 01B — it picks up exactly where this module stops: uv projects, asyncio properly, httpx, Pydantic, FastAPI, pytest.
Common misconceptions#
| Misconception | Reality |
|---|---|
| "Python is slow because it's interpreted." | CPython compiles to bytecode and runs a tight loop; heavy work happens in C extensions (NumPy, SDKs). Bottlenecks are algorithms and I/O. |
| "Python variables are typed boxes like Java's." | They're names bound to objects; a name can hold any type, and b = a aliases, never copies. |
"is is Python's ===." |
is is identity (same object); ===/==-equivalent is ==. Use is only for None/singletons. |
| "Python has no block scope, like PHP." | True — but PHP has function scope and Python adds module/class/comprehension scope; Java/JS let block scoping has no Python equivalent. |
""0" is falsy in Python like PHP." |
"0" is truthy in Python and JS; only "" is falsy. |
| "Empty list/dict is falsy in JS so it's falsy everywhere." | []/{} are truthy in JS, falsy in Python and PHP. |
"??/?. exist in Python." |
No operators — the idioms are .get(), x if x is not None else d, x or d (falsy caveat). |
"Python has const/final/private." |
No — UPPER_CASE and _/__ are conventions; enforcement is by review, not keywords. |
| "Java records ≈ Python classes I write by hand." | @dataclass(frozen=True) generates them; write boilerplate only when you need custom behaviour. |
"list.sort() returns the sorted list." |
It returns None and sorts in place; sorted() returns a new list. |
"+= on a list copies like x = x + [...]." |
+= mutates in place (__iadd__); + creates a new object. Aliases see the difference. |
| "Default arguments are evaluated per call." | They're evaluated once at def time — def f(x=[]) shares one list across all calls. |
| "Closures capture values." | They capture variables looked up at call time — the late-binding trap. |
| "Checked exceptions don't exist in Python." | Correct — all exceptions are unchecked; you catch by type hierarchy. |
"__init__ is the constructor." |
It's the initializer; __new__ constructs. Ticket(...) has no new keyword. |
| "Importing a module is free." | Top-level code runs on first import — guard side effects with if __name__ == "__main__":. |
"for loop variables are scoped to the loop." |
They leak into the enclosing scope — there's no block scope. |
"Java string templates / STR. exist." |
They were previewed in JDK 21–22 and withdrawn in JDK 23 — dead syntax in JDK 25/27. |
Key takeaways#
- Names, not boxes:
b = aaliases the same object;istests identity,==tests value (with__eq__), and there is no type juggling —"1" + 1raises. - No sigils, no semicolons, no braces: indentation is syntax; scope is function/module/class/comprehension only — no block scope, and loop variables leak.
- Truthy ≠ truthy: Python falsy =
False,None,0,0.0,"", empty containers."0","false","0.00"are truthy;[]/{}are falsy (unlike JS). Noneis the only missing value — distinct fromFalseand0; checkis None, get keys with.get(), letKeyError/NameError/TypeErrorsurface real bugs.- Collections split cleanly:
list(ordered, mutable),tuple(ordered, immutable),dict(insertion-ordered map — JSON objects are dicts),set(unordered, O(1) membership).sorted(key=...)is stable;list.sort()returnsNone. - Copying is shallow by default:
.copy()/[:]/{**d}share nested objects;copy.deepcopyfor full independence; prefer immutable types. - Functions: keyword args are the norm,
*args/**kwargsunpack, no overloading (use defaults), closures capture variables (late binding!), mutable default args are a shared-object trap. - OOP:
class X:,__init__initialises (nonew),selfexplicit,@property/@classmethod/@staticmethod,Protocolfor structural contracts,@dataclassfor records,Enum/StrEnumfor statuses — no enforcedprivate/final. - Errors:
try/except/else/finally,raise ... from, catch specific types,withfor guaranteed cleanup; all unchecked like JS/PHP, not Java's checked model. - Async:
async def/await/asyncio.gather≈Promise/async/await/Promise.all; the GIL limits threads to I/O waits —asynciois the LLM-call idiom (01B.3 owns it). - Tooling:
pyproject.toml+uv/pip+ PyPI ≈package.json/composer.json/pom.xml;venv≈node_modules/vendor/;ruff≈ ESLint+Prettier;pytest≈ Jest/JUnit/PHPUnit; FastAPI/Django/Flask ≈ Laravel/Express/Spring. - The surprises that bite: mutable defaults, late binding,
+=aliasing,sort()→None,isvs==,///%floor semantics, comprehension scope, module-level code on import,boolisint, no block scope,"0"truthy.
Where you'll use this in the AI path#
This lesson is the map — every later lesson is Python. The specific bridges:
| Skill from this lesson | Used in |
|---|---|
dict/list shapes, JSON round-trips |
03.2 Messages and Conversation State — message lists are nested dicts |
except specificity, raise ... from |
03.8 Errors, Rate Limits, Timeouts and Retries — provider exception taxonomy |
asyncio.gather, event loop |
03.9 Async, Concurrency and Batch and 01B.3 |
Protocol, classes, dataclass |
03.5 Tool Calling tool dispatch; 01B.6 Pydantic models |
pathlib, file I/O, generators |
05.1 Data Sources and Ingestion and 05.9 Ingestion Pipelines |
comprehensions, Counter, defaultdict |
everywhere — embeddings batches, eval metrics, prompt assembly |
| Type hints (not enforced) | 03.4 Structured Output — SDK signatures are hints; Pydantic validates |
pytest-style thinking, fakes |
01B.8 and 03.10 |
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Name binding | Python "variables" are labels on objects, not typed boxes |
| Object identity vs equality | is compares identity (same object); == calls __eq__ for value |
| Truthiness / falsy | Whether a value counts as true in if/and/or/not contexts |
| Type juggling | Silent cross-type conversion (PHP ==, JS ==, Number()) — absent in Python |
| EAFP | "Easier to ask forgiveness than permission": try/except over pre-checks |
| LBYL | "Look before you leap": pre-checking with in/hasattr/isset |
| LEGB | Local → Enclosing → Global → Builtins name-resolution order |
| Block scope | { }-delimited scope — absent in Python (function/module/class/comprehension only) |
| Mutable default argument | A def f(x=[]) default evaluated once, shared across calls |
| Late binding | Closures look up variables at call time, not def time |
| Name mangling | __x → _Class__x attribute renaming ("private" by convention) |
| Dunder method | Double-underscore magic method (__init__, __repr__, __eq__...) |
Protocol |
Structural typing contract — satisfied by shape, not inheritance |
dataclass |
Decorator generating __init__/__repr__/__eq__ for data holders |
Enum/StrEnum/IntEnum |
Named constant sets; StrEnum members equal their string value |
| Context manager | Object used with with for guaranteed setup/cleanup (__enter__/__exit__) |
| Exception chaining | raise NewError from cause preserving the original traceback |
| Event loop | The scheduler that runs async/await coroutines cooperatively |
| GIL | Global Interpreter Lock — serialises Python bytecode; limits thread parallelism |
| Virtual environment | Isolated Python + packages per project (venv/uv) |
pyproject.toml |
The PEP 621 project manifest (deps, tool config) |
__name__ == "__main__" |
Guard so a module's script-only code doesn't run on import |
| Comprehension scope | The hidden per-comprehension variable scope (loop vars don't leak) |
Naive vs aware datetime |
A datetime without / with a tzinfo; Python refuses to compare them. Store and compute in aware UTC |
| Coroutine (lazy) | The object an async def call returns; it does nothing until awaited or scheduled, unlike an eager JS Promise |
for/else |
else on a loop runs only if no break occurred |
| Insertion-ordered dict | dict preserves key insertion order (guaranteed 3.7+) |
| Shallow vs deep copy | .copy() shares nested objects; copy.deepcopy copies recursively |
sorted vs list.sort |
sorted() returns a new list; .sort() mutates and returns None |
All terms are also collected in the glossary.
Exercises#
Translate, predict and debug. Solutions inside <details>; deterministic outputs were run for real.
- Translate to Python: PHP
$greeting = "Hello, $name! You have " . count($items) . " items.";and the JS`Hello, ${name}! You have ${items.length} items.`— write the Python f-string. - Predict: what does
print("a" + 1)do in each of the four languages? Explain each. - Truthiness: for each of
[0, "0", "", [], {}, None, "false", -1], say whether it's truthy in PHP, JS and Python (three columns). isvs==: predictx = 1000; y = 1000; print(x is y, x == y)— then explain why theisresult is unreliable.- Mutable default: fix
def add(item, items=[]): items.append(item); return itemsso repeated calls don't accumulate, and explain why the original fails. - Late binding:
fs = [lambda: i for i in range(3)]— predict[f() for f in fs], then fix it two different ways. - Copying: given
a = [[1],[2]]; b = a; c = a.copy(); d = copy.deepcopy(a), predict the result ofa[0].append(9); b[0].append(8); c[1].append(7); d[0].append(6)— which lists see which appends? - Sort: rewrite
usort($tickets, fn($a,$b) => $a["p"] <=> $b["p"])and Javatickets.sort(Comparator.comparing(t -> t.p))as Python; then explain whyr = tickets.sort(key=...)followed byreturn rreturnsNone. - Missing value: translate
user?.address?.city ?? "unknown"(JS) and$user["address"]["city"] ?? "unknown"(PHP) to Python, handling the case whereaddressis absent and where it's present butcityis absent. - Exception: translate Java
try { int n = Integer.parseInt(s); } catch (NumberFormatException e) { ... }to Python, preserving the exception type and message. - Module import: write a two-file example proving that importing a module runs its top-level code once, and guard it with
if __name__ == "__main__":. ///%: compute-7 // 2,-7 % 2,divmod(-7, 2)and compare with Java-7 / 2,-7 % 2— where would a ported algorithm break?- Fast track: pick one language you know and write the 5 gotchas from Part 11 you'd check first, with a one-line Python demo each.
- Idiom table: for rows 8, 19 and 35 of Part 8, write a runnable Python snippet proving each works as shown.
- Four-language program: in Part 10, the Python version uses
defaultdict+Counter. Rewritesummarisewithout them (plaindict+ manual counting) and confirm it prints the same output. - Time zones and laziness. (a) Create an aware UTC
datetime, add 30 days, and show what happens when you compare it with a naive one. (b) Call anasync deffunction withoutawaitand show what Python prints.
Solutions
f"Hello, {name}! You have {len(items)} items."— f-strings interpolate expressions directly;{len(items)}calls the function inside the braces.- PHP:
"a" + 1→TypeError: Unsupported operand types: string + int— since PHP 8.0 a non-numeric string in arithmetic is fatal (PHP 7 only warned and computed1). Note.is PHP's concat operator, so"a" . 1would give"a1"— but that's a different expression. JS:"a1"—+concatenates when either operand is a string. Java:"a1"too —+is overloaded and concatenates whenever aStringis involved (1 + "a"gives"1a"); what Java won't compile is arithmetic on incompatible non-String types. Python:TypeError: can only concatenate str (not "int") to str. Only Python refuses outright; PHP throws only for non-numeric strings ("1" + 1→2happily). - Truthy: PHP —
0✗"0"✗""✗[]✗{}→n/a ({}isn't a PHP value;new stdClasswould be truthy)None→null✗"false"✓-1✓. JS —0✗"0"✓""✗[]✓{}✓null✗"false"✓-1✓. Python —0✗"0"✓""✗[]✗{}✗None✗"false"✓-1✓. Key diffs:"0"(PHP✗ others✓),[]/{}(JS✓ others✗). PHP column note: readNoneasnull; PHP has no{}literal —new stdClassis the nearest empty object (truthy). x is y→Truein this exact snippet — but not because 1000 is special: CPython merges the two identical literals into one constant object within the same code object, an implementation detail, not a guarantee (that's why 9.11 hedges).x == y→Truealways — value equality is the contract.int("1000") is int("1000")→False— separately computed ints are different objects. Use==for value,isonly forNone/singletons.def add(item, items=None): if items is None: items = []; items.append(item); return items—Nonedefault is created fresh per call; the shared[]was evaluated once atdef.- Predict
[2, 2, 2]— all lambdas share the samei(late binding). Fix 1:[lambda i=i: i for i in range(3)](default binds early). Fix 2:def make(i): return lambda: ithen[make(i) for i in range(3)](each call gets its owni). - Verified by running.
a[0].append(9)→a=[[1,9],[2]];baliasesa, sob[0].append(8)→a[0]==[1,9,8]andb is astill.c = a.copy()is shallow:cgets its own outer list butc[0]isa[0]andc[1]isa[1]— the same inner list objects. Soc[1].append(7)mutatesa[1]too:abecomes[[1,9,8],[2,7]].d = copy.deepcopy(a)is fully independent, sod[0].append(6)→d=[[1,6],[2]](anddwas copied before the appends, so it shows the original[1]/[2]plus the 6). Final state:a = [[1,9,8],[2,7]],bprints identically (same object),cprints[[1,9,8],[2,7]]too — same values but a different outer list whose inner lists are the very same objects asa's — and onlyd = [[1,6],[2]]is insulated. The lesson: a shallow copy shares every inner list, not just the first. sorted(tickets, key=lambda t: t["p"])—key=not a comparator; multi-keykey=lambda t: (t["p"], t["name"])..sort()returnsNonebecause it sorts in place (Java'sList.sortalso returns void); usesorted()to get a new list.city = (user.get("address") or {}).get("city", "unknown")— but that conflates missingaddresswithcityabsent. Precise:addr = user.get("address") or {}; city = addr.get("city", "unknown") if isinstance(addr, dict) else "unknown". Simpler idiom:user.get("address", {}).get("city", "unknown")works whenaddressis absent or{}, but fails ifaddressis present-but-None— then.getonNoneraisesAttributeError. The robust version checksisinstance.try: n = int(s)\nexcept ValueError as e: ...—int()raisesValueError(likeNumberFormatException), messageinvalid literal for int() with base 10: '...'.mod.pywithprint("top level ran")andmain.pywithimport mod→ prints once. Addif __name__ == "__main__":aroundmod.py's print → importingmodno longer prints; runningpython mod.pystill does.- Python:
-7 // 2 == -4,-7 % 2 == 1,divmod(-7,2) == (-4,1). Java:-7 / 2 == -3(truncates toward zero!),-7 % 2 == -1. So Python floors, Java truncates — a ported//-as-/breaks on negatives. - (Example for PHP) 1)
+=vs+on lists:x=[1];y=x;x+=[2]→ both[1,2]. 2) mutable defaultdef f(a=[]). 3)isvs==:[1] is [1]→False. 4)"0"truthy:bool("0")→True. 5) module code on import. - Row 8:
user.get("address", {}).get("city")→Noneif either missing. Row 19:list(dict.fromkeys([3,1,3,2,1]))→[3,1,2]. Row 35:[x for row in [[1,2],[3]] for x in row]→[1,2,3]. - Plain-
dictversion (ran it — output is byte-identical to thedefaultdict/Counterversion):
def summarise(path):
tickets = json.loads(Path(path).read_text(encoding="utf-8"))
by_status = {} # status -> list of tickets
for t in tickets:
by_status.setdefault(t["status"], []).append(t)
print(f"{len(tickets)} tickets")
for status in sorted(by_status):
group = by_status[status]
priorities = {} # priority -> count
for t in group:
p = t["priority"]
priorities[p] = priorities.get(p, 0) + 1
print(f" {status}: {len(group)}")
for p in ("low", "normal", "high"):
if priorities.get(p):
print(f" {p}: {priorities[p]}")setdefault replaces defaultdict(list); priorities.get(p, 0) + 1 replaces Counter. Running it on tickets.json prints exactly the Output: block in Part 10 — same grouping, same counts, no collections imports needed.
16. (a) The code and output are in 2.7: datetime(2026, 11, 6, 9, 30, tzinfo=UTC) + timedelta(days=30) gives 2026-12-06 09:30:00+00:00, and aware < naive raises TypeError: can't compare offset-naive and offset-aware datetimes. (b) Run for real:
import asyncio
async def fetch(label):
return label
async def main():
fetch("a") # forgot await: nothing runs
print("main finished")
asyncio.run(main())na.py:7: RuntimeWarning: coroutine 'fetch' was never awaited
fetch("a") # forgot await: nothing runs
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
main finishedThe call created a coroutine object and discarded it, so fetch never ran. Fix: await fetch("a"), or schedule it with asyncio.create_task(...) / asyncio.gather(...).
Check yourself#
- In Python, what does
b = ado whenais a list — copy or alias? How do you tell?Alias —bbecomes another name for the same list object.a is b→True;a == b→Truebut that's value equality. Mutating throughbshows ina. - Why does
"1" + 1raise in Python but not in PHP or JS?Python doesn't coerce types in+:str + intis aTypeError. PHP casts"1"→1, JS coerces to string"11". Python requires explicitint("1") + 1. - Name three values that are falsy in Python but have different "missing/empty" meanings (
None,0,"",[]...).None(missing),0/0.0(numeric zero),""(empty string),[]/{}/()/set()(empty containers) — all falsy but semantically different;is Nonechecks missing specifically. - What's the difference between
x == yandx is y? When isiscorrect?==calls__eq__(value);iscompares object identity.isis correct only for singletons:x is None,x is True, sentinel objects — never for value comparison. - Why is there no block scope in Python, and what are the four scope types?Python scope is created by module, function, class and comprehension — not by
if/for/while/with/tryblocks. Loop variables leak into the enclosing scope. - PHP's
if (!$x)guard — what Python construct checks "missing" vs "falsy", and why do they differ?if x is Nonechecks missing;if not xchecks falsy (also catches0,"",[]). PHP's!$xconflates them; Python forces the choice. def f(items=[])— why does the list persist across calls, and what's the fix?The default[]is evaluated once atdeftime and shared by every call. Fix:items=Nonethen create[]inside whenitems is None.[lambda: i for i in range(3)]returns[2,2,2]— explain and give two fixes.Late binding — all lambdas share the loop variablei, which is2when called. Fixes:lambda i=i: i(bind early) or adef make(i): return lambda: ifactory (each call gets its owni).list.sort()vssorted(): what does each return and which mutates?list.sort()sorts in place and returnsNone;sorted()returns a new sorted list. Use.sort()to mutate,sorted()to keep the original.- Why does
x += [2]affect an aliasy = xbutx = x + [2]doesn't?+=calls__iadd__→list.extendin place (same object).+builds a new list and rebindsx. The aliasystill points at the old object in the second case. - Java
==on objects vs Pythonis— are they the same idea? What's the Python equivalent of Java's.equals()?No — Java==on objects is reference equality (likeis), but Java's.equals()is the value check (like==). Python merges the concepts:==is value,isis identity. try (Resource r = ...)in Java,usingin JS — what's the Python equivalent and what does it guarantee?with— the context manager protocol (__enter__/__exit__). It guarantees cleanup on block exit, including on exception.- Why does
import mymodulesometimes print output or take time, and how do you prevent it?Top-level module code runs once on first import (cached insys.modules). Prevent it by guarding side effects behindif __name__ == "__main__":and keeping imports side-effect-free. -7 % 2in Python vs Java — what are the values and why do they differ?Python-7 % 2 == 1(sign of divisor, floor division); Java-7 % 2 == -1(sign of dividend, truncation).//in Python is floor division (-4); Java/on ints truncates toward zero (-3).- Which 01A lesson should a PHP developer read first after this one, and which can they skip?
Further resources#
- Python docs — Language Reference: the authoritative semantics (data model, expressions, statements). Start with Datamodel and Expressions.
- Python docs —
stdtypes: truth-value testing and the built-in types. - PEP 8 — Style Guide: naming and formatting conventions.
- The Python Tutorial: official beginner path (skim if you know another language).
- Real Python: practical articles; the "Python for X developers" series.
- PHP manual: Types, Comparison, Type juggling.
- MDN JavaScript: Truthy, Equality, Array.prototype.sort.
- Java: JLS §15.21.3 Reference Equality, Java Tutorials, JEP index.
- Version trackers: python.org/downloads, php.net/supported-versions, nodejs.org, openjdk.org.
← 01A.10 — Type Hints and Writing Readable Code | Module 01A overview | Module 01B: Python for AI Engineering →