Topic 55 of 64
Positional Arguments
Overview
Positional arguments are matched to parameters by position (left to right). They are the most basic and common argument type — used in virtually every function call. Understanding their order requirements prevents common TypeError bugs.
Syntax
python
def connect(host: str, port: int, timeout: float):
return f"Connecting to {host}:{port} (timeout={timeout}s)"
# Positional — order matters
connect("localhost", 5432, 30.0)
# You can also pass positionally by keyword (named)
connect("localhost", timeout=30.0, port=5432) # same result
# Positional-only params (Python 3.8+, before /)
def add(x, y, /): # x and y can ONLY be positional
return x + yCommon Pitfalls
- Positional arguments are required unless they have a default value — missing one raises TypeError.
- Once you use a keyword argument in a call, all subsequent arguments must also be keyword.
- Interview tip: Function signature order convention: required positionals → optional with defaults → *args → keyword-only → **kwargs.
Real-World Example
Database connection factory using positional argument ordering
example
python
def create_connection(
host: str,
port: int,
database: str,
user: str = "admin",
password: str = "",
) -> dict:
return {
"host": host, "port": port,
"database": database, "user": user,
"password": password,
}
# All positional
conn = create_connection("db.example.com", 5432, "mydb")
print(conn)