Advanced Functions & Parameters
Published by Brayan K
Master every advanced Python function technique — from closures and decorators to metaprogramming, function factories, and production-level patterns used by FAANG engineers.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
What this lesson covers, and where the rest lives
Each of the bigger function techniques has a lesson of its own: Closures & Lexical Scope in Real Projects, Decorators & Advanced Features, Higher-Order Functions & Function Factories and Metaprogramming & Introspection with inspect. This one is about parameters, the part every function has. It builds on Functions, which covered defaults and keyword arguments, and *args & **kwargs, which covered collecting and spreading arguments and the bare *. It adds the parameters that can't be named, why keyword-only ones exist, when default values are made, how Python matches arguments to parameters, and functions that call themselves.
Parameters that can't be named: the / marker
Some built-in functions refuse an argument given by name. inspect.signature(), from the standard library's inspect module, shows a function's parameter list, and the / in it says which parameters are positional-only:
import inspect
print(inspect.signature(len))
print(inspect.signature(sorted))
print(len([1, 2, 3]))
print(len(obj=[1, 2, 3]))
# ✅ Expected output:
# (obj, /)
# (iterable, /, *, key=None, reverse=False)
# 3
# ✅ Expected error:
# TypeError: len() takes no keyword argumentsParameters before the / can only be given by position, so len(obj=...) is refused. In sorted's list, the * makes key and reverse keyword-only, which is why Lambda Functions had to write key=. Your own functions can use / too, since Python 3.8:
def describe(name, /, sep=": "):
return "Name" + sep + name
print(describe("Ada"))
print(describe("Ada", sep=" -> "))
print(describe(name="Ada"))
# ✅ Expected output:
# Name: Ada
# Name -> Ada
# ✅ Expected error:
# TypeError: describe() got some positional-only arguments passed as keyword arguments: 'name'Why refuse a name? Because then the name is free for something else. A function that takes any number of keyword arguments with **attrs can still receive one called name:
def tag(name, /, **attrs):
return name, attrs
print(tag("a", name="link", href="/home"))
# ✅ Expected output:
# ('a', {'name': 'link', 'href': '/home'})Without the /, the keyword collides with the parameter:
def tag(name, **attrs):
return name, attrs
print(tag("a", name="link", href="/home"))
# ✅ Expected error:
# TypeError: tag() got multiple values for argument 'name'A positional-only parameter can also be renamed later without breaking any code that calls the function, because no call can have used its name.
Keyword-only parameters keep look-alike values apart
*args & **kwargs showed that parameters after a bare * must be named. That's worth doing whenever two arguments could be swapped without anyone noticing, such as two account names:
def transfer(amount, *, source, target):
return f"{amount} from {source} to {target}"
print(transfer(50, source="savings", target="current"))
print(transfer(50, "savings", "current"))
# ✅ Expected output:
# 50 from savings to current
# ✅ Expected error:
# TypeError: transfer() takes 1 positional argument but 3 were givenIt's just as useful for a True/False flag, since a bare True in a call says nothing about what it switches on. The error for a flag passed by position is worth reading slowly:
def save(text, *, overwrite=False):
return "saved" if overwrite else "kept"
print(save("notes", overwrite=True))
print(save("notes", True, overwrite=True))
# ✅ Expected output:
# saved
# ✅ Expected error:
# TypeError: save() takes 1 positional argument but 2 positional arguments (and 1 keyword-only argument) were given"2 positional arguments" are "notes" and True; "(and 1 keyword-only argument)" is overwrite=True, which was fine. Only one positional argument fits.
The full parameter order
All the kinds can appear in one def, always in this order: positional-only, then /, then ordinary parameters, then *args (or a bare *), then keyword-only parameters, then **kwargs.
def f(a, /, b, *args, c, d=4, **kwargs):
print("a =", a, "| b =", b, "| args =", args)
print("c =", c, "| d =", d, "| kwargs =", kwargs)
f(1, 2, 3, 4, c=5, e=6)
f(1, b=2, c=3)
# ✅ Expected output:
# a = 1 | b = 2 | args = (3, 4)
# c = 5 | d = 4 | kwargs = {'e': 6}
# a = 1 | b = 2 | args = ()
# c = 3 | d = 4 | kwargs = {}Here a can only come by position, b either way, c only by name, and d has a default. A name that matches a positional-only parameter isn't an error when there's a **kwargs: it simply lands there.
def f(a, /, b, *args, c, d=4, **kwargs):
print(a, b, args, c, d, kwargs)
f(1, 2, c=3, a=9)
# ✅ Expected output:
# 1 2 () 3 4 {'a': 9}Python checks the order when it reads the file, before anything runs: parameters in the wrong order stop the whole program with a SyntaxError, whose wording differs between Python versions.
Default values are made once, when def runs
A default isn't worked out on each call. Python evaluates it once, when the def itself runs, and keeps that value for every call that leaves the argument out, as the Python language reference says. Watch when the default is made:
def start_list():
print("making the default list")
return []
def add_item(item, items=start_list()):
items.append(item)
return items
print("def has run")
print(add_item("a"))
print(add_item("b"))
# ✅ Expected output:
# making the default list
# def has run
# ['a']
# ['a', 'b']There was one list, made before any call, and both calls added to it. The same happens with items=[], which is the trap Functions warned about. __defaults__ shows the default values the function keeps:
def add_item(item, items=[]):
items.append(item)
return items
print(add_item("a"))
print(add_item("b"))
print(add_item.__defaults__)
# ✅ Expected output:
# ['a']
# ['a', 'b']
# (['a', 'b'],)The usual fix is a default of None, which is never changed, and a new list made inside the function when none was passed. is None is from Operators and Expressions; None & NoneType has more on None as a placeholder.
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
print(add_item("a"))
print(add_item("b"))
print(add_item.__defaults__)
# ✅ Expected output:
# ['a']
# ['b']
# (None,)The same rule explains when a default's errors appear. A default that names something undefined fails as the def runs, before any call and before the next line:
def greet(name, greeting=default_greeting):
return greeting + ", " + name
print("never reached")
# ✅ Expected error:
# NameError: name 'default_greeting' is not definedHow Python matches arguments to parameters
Every call is matched to the parameters the same way, before the function's body starts:
- positional arguments fill the parameters from the left;
- each keyword argument fills the parameter with its name, and one already filled is an error;
- parameters still empty take their default values;
- any parameter still empty after that is an error.
So argument errors are about the call, never about the code inside the function, and their messages count only what the call can fill:
def area(width, height=1):
return width * height
print(area(3))
print(area(3, 2))
print(area(3, 2, 1))
# ✅ Expected output:
# 3
# 6
# ✅ Expected error:
# TypeError: area() takes from 1 to 2 positional arguments but 3 were givenWith a default, the message gives a range: area() takes 1 or 2 positional arguments. Arguments spread from a dictionary with ** are matched like keywords, so a key with no parameter of that name is refused:
def area(width, height=1):
return width * height
sizes = {"width": 3, "height": 2}
print(area(**sizes))
sizes["depth"] = 1
print(area(**sizes))
# ✅ Expected output:
# 6
# ✅ Expected error:
# TypeError: area() got an unexpected keyword argument 'depth'Recursion: a function that calls itself
A function can call itself, on a smaller version of the problem, until it reaches a case it can answer directly, called the base case. Each call waits for the one it made:
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(5))
print(factorial(1))
# ✅ Expected output:
# 120
# 1factorial(5) is 5 × factorial(4), and so on down to factorial(1), which answers 1 without calling anything. Recursion earns its place on data that nests, like the nested data in Working with JSON, where a loop doesn't know how deep to go. isinstance() is from Inheritance and Polymorphism:
def total(values):
result = 0
for value in values:
if isinstance(value, list):
result += total(value)
else:
result += value
return result
print(total([1, 2, 3]))
print(total([1, [2, 3], [4, [5, 6]]]))
# ✅ Expected output:
# 6
# 21Without a base case, the calls never stop on their own. Python stops them, about a thousand calls deep:
def countdown(n):
return countdown(n - 1)
countdown(3)
# ✅ Expected error:
# RecursionError: maximum recursion depth exceededThe recursive line must return its result too, or the call above it gets None:
def factorial(n):
if n <= 1:
return 1
n * factorial(n - 1)
print(factorial(5))
# ✅ Expected error:
# TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'factorial(2) works out 2 × 1 and drops it, so factorial(3) tries 3 × None. The limit on depth is sys.getrecursionlimit(), 1000 by default, so recursion suits data a few hundred levels deep at most; a loop has no such limit.
import sys
def sum_to(n):
if n == 0:
return 0
return n + sum_to(n - 1)
print(sys.getrecursionlimit())
print(sum_to(900))
# ✅ Expected output:
# 1000
# 405450Recursion can also repeat work: a recursive Fibonacci function works out the same small values hundreds of thousands of times. functools.lru_cache remembers each result. Wrapping the function and putting the cached version back under its own name, so the recursive calls use it too, cuts the calls for fib(30) from 2,692,537 to 31:
from functools import lru_cache
calls = []
def fib(n):
calls.append(n)
return n if n < 2 else fib(n - 1) + fib(n - 2)
fib = lru_cache(maxsize=None)(fib)
print(fib(30), len(calls))
# ✅ Expected output:
# 832040 31functools: lru_cache, partial, reduce covers caching in full.
Practice: a scoreboard with a safe default
add_score() records a score on a scoreboard dictionary and returns it. Fill the blanks so the player's name can only be given by position, and each call without a board gets a new one. The three hints under the code answer the blanks from top to bottom.
def add_score(name, ___, score, *, board=___):
if board is ___:
board = {}
board[name] = score
return board
first = add_score("Ada", 90)
second = add_score("Linus", 75)
print(first)
print(second)
print(add_score("Grace", 88, board=first))
# 👉 replace ___ with /
# 👉 replace ___ with None
# 👉 replace ___ with None
# ✅ Expected output:
# {'Ada': 90}
# {'Linus': 75}
# {'Ada': 90, 'Grace': 88}Run it before filling anything in, and it stops at the def line with NameError: name '___' is not defined: the default ___ is worked out when the def runs. With board={} instead of None, Ada and Linus would end up on one shared board.
On your own: the last few scores
Write record(score, /, *, history=None, keep=3):
- it adds score to history, using a new list when none is passed;
- it removes the oldest scores, with pop(0), until at most keep are left;
- it returns the list;
- score can't be passed by name.
Call it twice with no history, then record 1, 2, 3 and 4 into a list of your own, then record 9 with keep=2, printing each result, and finally try record(score=5). If your first two calls print [5] and then [5, 7], the default list is shared.
# Write record(score, /, *, history=None, keep=3) here.
# your code heredef record(score, /, *, history=None, keep=3):
if history is None:
history = []
history.append(score)
while len(history) > keep:
history.pop(0)
return history
print(record(5))
print(record(7))
mine = []
for points in [1, 2, 3, 4]:
record(points, history=mine)
print(mine)
print(record(9, history=mine, keep=2))
print(record(score=5))
# ✅ Expected output:
# [5]
# [7]
# [2, 3, 4]
# [4, 9]
# ✅ Expected error:
# TypeError: record() got some positional-only arguments passed as keyword arguments: 'score'
Practice quiz
def add_item(item, items=[]): items.append(item); return items. A program runs add_item("a"), then print(add_item("b")). What prints?
- ['b']
- ['a']
- ['a', 'b']
- It stops with a TypeError
Answer: ['a', 'b']. The default list was made once, when def ran, and both calls appended to that same list.
The same add_item, but its body is items = items + [item]; return items. After add_item("a"), what does print(add_item("b")) show?
- ['a', 'b']
- ['b']
- []
- It stops with an UnboundLocalError
Answer: ['b']. items + [item] makes a new list and rebinds the name, so the shared default stays empty.
greeting = "Hello"; def greet(name, greeting=greeting): return greeting + ", " + name. Then greeting = "Hi", then print(greet("Ada")). What prints?
- Hi, Ada
- It stops with a NameError
- Hello, Ada
- greeting, Ada
Answer: Hello, Ada. The default was worked out when def ran, while greeting was still "Hello".
def point(x, y, /): return (x, y). What does print(point(1, y=2)) do?
- It stops with TypeError: point() got some positional-only arguments passed as keyword arguments: 'y'
- It prints (1, 2)
- It prints (2, 1)
- It stops with TypeError: point() got an unexpected keyword argument 'y'
Answer: It stops with TypeError: point() got some positional-only arguments passed as keyword arguments: 'y'. The / makes x and y positional-only, so y=2 is refused by name.
def resize(image, *, width, height). What does resize("cat.png", 100, 50) do?
- It returns ('cat.png', 100, 50)
- It stops with TypeError: resize() missing 2 required keyword-only arguments: 'width' and 'height'
- It stops with a SyntaxError
- It stops with TypeError: resize() takes 1 positional argument but 3 were given
Answer: It stops with TypeError: resize() takes 1 positional argument but 3 were given. Everything after the * must be named, so only image can be passed by position.
def f(a, /, b, *args, c, **kwargs): print(args). What does f(1, 2, 3, 4, c=5) print?
- (2, 3, 4)
- (3, 4)
- [3, 4]
- ()
Answer: (3, 4). 1 and 2 fill a and b, the extra positional arguments go to args as a tuple, and c is named.
def tag(name, /, **attrs): return attrs. What does print(tag("a", name="link")) show?
- {}
- It stops with TypeError: tag() got multiple values for argument 'name'
- ('a', 'link')
- {'name': 'link'}
Answer: {'name': 'link'}. name is positional-only, so the keyword name="link" can't fill it and lands in attrs instead.
def total(n): if n == 0: return 0, else the last line is n + total(n - 1) with no return. What does print(total(3)) do?
- It stops with TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
- It prints 6
- It prints None
- It stops with RecursionError
Answer: It stops with TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'. total(1) adds but returns None, so total(2) tries 2 + None. A recursive step must return its result too.
Continue this course
- Previous: Decorators & Advanced Features
- Next: Higher-Order Functions & Function Factories — Pass and return functions, build factories and pipelines
- Quick reference: Python cheat sheet
Frequently asked questions
Can a lambda use / and *?
Yes, with the same meaning as in def. first = lambda a, /, b=0: a + b makes a positional-only a, so first(1, b=2) gives 3, and pick = lambda *, key: key must be called as pick(key="x").
Why does one error message say __main__.area() instead of area()?
When the same keyword arrives twice through ** and an ordinary keyword, as in area(**{"width": 4}, width=5), Python names the function together with its module, and the program you run is the module __main__. The message reads TypeError: __main__.area() got multiple values for keyword argument 'width'.
Where does Python keep a function's default values?
On the function: __defaults__ holds the defaults of parameters that can be given by position, as a tuple, and __kwdefaults__ those of keyword-only parameters, as a dict. For def f(a, /, b=2, *args, c, d=4, **kwargs), they are (2,) and {'d': 4}.
Does Python turn a recursive call at the end of a function into a loop?
No. Some languages do that (it's called tail-call optimisation), but Python keeps every call on the stack, so a function that recurses 5,000 times stops with RecursionError even when the call is the last thing it does. Write a loop for deep repetition.
Is a mutable default ever useful?
Sometimes, on purpose, as a cache that lives as long as the function: def square(n, _cache={}) can keep each answer and skip the work the second time. It surprises readers, though, and functools: lru_cache, partial, reduce does the same job properly.