Skip to content

Latest commit

 

History

History
588 lines (403 loc) · 6.66 KB

python_semantics.md

File metadata and controls

588 lines (403 loc) · 6.66 KB

Python Semantics Checklist for Coding Agents

Purpose

Use this checklist when writing, reviewing, debugging, or refactoring Python code. Goal: avoid common semantic mistakes in indexing, mutability, assignment, function calls, iteration, comparison, and imports.

Core Mental Model

Python code should be reasoned from these principles:

name binding > object copying
mutable object > in-place side effects
half-open intervals > stop excluded
truthiness > explicit boolean conversion not always needed
identity != equality

1. Indexing and Slicing

Half-Open Slicing

Python slices use:

a[start:stop]

Meaning:

include start
exclude stop

So:

a[i : i + 10]

accesses indices:

i <= k < i+10

It does not access i+10.

Range Uses Same Rule

range(n)

produces:

0, 1, ..., n-1

Not n.

Negative Indexing

a[-1]

means:

last element

Common patterns:

a[-1]  # last item
a[:-1]  # all except last item
a[-2:]  # last two items

Slice Out-of-Bounds Is Safe

a[100:200]

returns:

[]

But:

a[100]

raises:

IndexError

Reverse Slice

a[::-1]

returns a reversed copy.

2. Assignment and References

Assignment Does Not Copy

b = a

means:

bind name b to same object as a

It does not create a new object.

Risk:

a = [1, 2]
b = a
b.append(3)

# a is now [1, 2, 3]

Use Explicit Copy When Needed

b = a.copy()
b = a[:]

For nested structures, shallow copy may still share inner objects.

Use:

import copy

b = copy.deepcopy(a)

when independent nested objects are required.

3. Mutability

Mutable Objects Can Change In Place

Examples:

list
dict
set
a = [1, 2]
a.append(3)

Immutable Objects Cannot Change In Place

Examples:

int
float
str
tuple
frozenset
s = "abc"
s[0] = "x"  # TypeError

Create a new object instead:

s = "x" + s[1:]

4. In-Place Methods

Methods that mutate objects usually return:

None

Example:

a = [3, 1, 2]
a.sort()

Correct.

Avoid:

a = a.sort()

because a becomes:

None

Common in-place methods:

list.append()
list.extend()
list.sort()
list.reverse()
dict.update()
set.add()

5. Mutable Default Arguments

Avoid mutable default values:

def f(x, bag=[]):
    bag.append(x)
    return bag

Problem:

same list reused across calls

Use:

def f(x, bag=None):
    if bag is None:
        bag = []
    bag.append(x)
    return bag

6. Truthiness

Python treats empty values as false.

False-like values:

None
False
0
0.0
""
[]
()
{}
set()

Preferred:

if items:
    ...

Instead of:

if len(items) > 0:
    ...

Use explicit checks when meaning matters:

if x is None:
    ...

not:

if not x:
    ...

when 0, "", or [] are valid values.

7. Boolean Operators

and and or return operands, not always booleans.

value = user_input or default_value

Meaning:

if user_input is truthy, use user_input
else use default_value

Examples:

"hello" or "world"  # "hello"
"" or "world"  # "world"
"hello" and "world"  # "world"
"" and "world"  # ""

8. Equality vs Identity

Equality

a == b

means:

same value

Identity

a is b

means:

same object

Example:

a = [1, 2]
b = [1, 2]

a == b  # True
a is b  # False

Use identity for None:

if x is None:
    ...

Avoid:

if x == None:
    ...

9. Chained Comparisons

Python supports mathematical comparison chains:

1 < x < 10

Meaning:

1 < x and x < 10

Preferred for range checks.

10. Augmented Assignment

+= may mutate in place.

For lists:

a = [1, 2]
b = a

a += [3]

# both a and b see [1, 2, 3]

For immutable objects:

x = (1, 2)
x += (3,)

creates a new tuple.

Agent rule:

check object mutability before using +=

11. List Multiplication Trap

Avoid this for nested lists:

matrix = [[0] * 3] * 3

Problem:

inner lists share same reference

Use:

matrix = [[0] * 3 for _ in range(3)]

12. Iteration

Prefer direct iteration:

for item in items:
    ...

Use enumerate when index is needed:

for i, item in enumerate(items):
    ...

Avoid unnecessary index loops:

for i in range(len(items)):
    ...

unless index arithmetic is required.

13. Dictionary Access

Dictionary lookup is by key, not position.

d["name"]

Use safe access when key may be missing:

d.get("name")
d.get("name", default_value)

Use membership check when needed:

if "name" in d:
    ...

14. Functions Are Objects

Functions can be:

assigned
passed as arguments
returned from functions
stored in data structures

Example:

def square(x):
    return x * x


f = square
f(5)

Useful for callbacks, decorators, strategies, and higher-order functions.

15. Comprehensions Create New Collections

b = [x * 2 for x in a]

creates a new list.

It does not mutate a.

Use comprehension for transformation. Use loops or in-place methods for mutation.

16. Import Behavior

A module is usually executed once per Python process, then cached in:

sys.modules

Use:

if __name__ == "__main__":
    main()

to prevent script logic from running during import.

Agent Review Checklist

Before finalizing Python code, verify:

[ ] Slice stop index intentionally excluded
[ ] range stop value intentionally excluded
[ ] negative indices are intentional
[ ] slicing vs indexing error behavior considered
[ ] assignment does not accidentally share mutable objects
[ ] copy / deepcopy used when needed
[ ] mutable default arguments avoided
[ ] in-place methods not assigned back accidentally
[ ] truthiness does not hide valid values like 0 or ""
[ ] is used only for identity checks, especially None
[ ] == used for value equality
[ ] += does not create unwanted mutation
[ ] nested list multiplication avoided
[ ] enumerate used when index is needed
[ ] dict keys handled safely
[ ] import side effects controlled with __main__ guard

Final Rule

When uncertain, ask:

Am I creating a new object, or mutating / referencing an existing object?

This single question prevents most Python semantic bugs.