PY

Variables & Types

Python · 8 entries

Variable Assignment

syntax
name = value
example
username = "alice"
age = 30
is_active = True
output
# alice, 30, True

Note Python variables are references to objects, not fixed memory boxes. No declaration keyword is needed.

Type Hints / Annotations

syntax
name: type = value
example
price: float = 19.99
items: list[str] = ["apple", "bread"]
user_map: dict[str, int] = {"alice": 1}
output
# No runtime enforcement — hints are for tools and readers

Note Type hints do not prevent wrong types at runtime. Use mypy or pyright for static checking. Since 3.12, you can use the new type statement for aliases.

Multiple Assignment

syntax
a, b, c = val1, val2, val3
example
x, y, z = 10, 20, 30
first, *rest = [1, 2, 3, 4, 5]
print(first, rest)
output
1 [2, 3, 4, 5]

Note The starred variable (*rest) captures remaining items as a list. Only one starred variable is allowed per assignment.

Type Checking at Runtime

syntax
type(obj)
isinstance(obj, ClassName)
example
score = 95.5
print(type(score))
print(isinstance(score, (int, float)))
output
<class 'float'>
True

Note Prefer isinstance() over type() == because isinstance handles subclasses correctly. The second arg can be a tuple of types.

None (Null Value)

syntax
variable = None
example
result = None
if result is None:
    print("No result yet")

# Common pattern: optional return
def find_user(user_id: int) -> str | None:
    return None
output
No result yet

Note Always compare to None with 'is' or 'is not', never == or !=. None is a singleton object.

Constants (Convention)

syntax
UPPER_SNAKE_CASE = value
example
MAX_RETRIES = 3
BASE_URL = "https://api.example.com"
PI = 3.14159

Note Python has no true constants. ALL_CAPS naming is a convention that signals 'do not reassign'. The typing.Final hint can be checked by type checkers.

Dynamic Typing & Reassignment

syntax
name = value1
name = value2  # different type is allowed
example
data = 42
print(type(data))
data = "now a string"
print(type(data))
output
<class 'int'>
<class 'str'>

Note Python is dynamically typed, so a variable can be rebound to any type. Type hints help catch accidental rebinding via static analysis.

Type Aliases (3.12+)

syntax
type AliasName = existing_type
example
type UserId = int
type Coordinate = tuple[float, float]
type UserMap = dict[UserId, str]

position: Coordinate = (40.71, -74.01)

Note The type statement (Python 3.12+) replaces TypeAlias from typing. It supports lazy evaluation and generic parameters.