Different Types of Arguments
Python offers several ways to pass arguments into a function, giving you flexibility in how a function can be called. Understanding each type helps you write functions that are both powerful and easy to use.
Positional Arguments
Values are matched to parameters based purely on their order in the function call.
def divide(a, b):
return a / b
divide(10, 2) # a = 10, b = 2
Keyword Arguments
Values are passed using the parameter's name, so the order in which you pass them no longer matters.
divide(b=2, a=10) # same result as above
Default Arguments
As covered earlier, these use a fallback value when no argument is explicitly supplied for that parameter.
Arbitrary Arguments: *args and **kwargs
*args lets a function accept any number of positional arguments as a tuple, while **kwargs lets it accept any number of keyword arguments as a dictionary.
def total(*args):
return sum(args)
total(1, 2, 3, 4) # 10
def show_details(**kwargs):
for key, value in kwargs.items():
print(key, ":", value)
show_details(name="Abhay", course="Data Science")
Coming Up Next
With argument types covered, the next section looks at how variables behave differently depending on where they are defined, starting with global variables.
The Order Rules for Parameters
When a function mixes several kinds of parameters, Python expects them in a fixed order. Breaking the order gives a SyntaxError before the code even runs.
- Regular positional parameters
- Parameters with default values
*args- Keyword-only parameters
**kwargs
def report(title, rows, sep=",", *extra, show_header=True, **options):
print(title, rows, sep, extra, show_header, options)
report("Sales", 120, ";", "draft", show_header=False, colour="blue")
# Sales 120 ; ('draft',) False {'colour': 'blue'}
In a call, positional values must also come before keyword values. report(title="Sales", 120) is an error.
Keyword-Only and Positional-Only Parameters
A bare * in the definition means every parameter after it must be passed by name. This is useful for flags that would be confusing as plain positional values. Compare load_csv("data.csv", False) with load_csv("data.csv", skip_blank=False): only the second one tells a reader what False controls.
def load_csv(path, *, encoding="utf-8", skip_blank=True):
...
load_csv("data.csv", encoding="latin-1") # fine
load_csv("data.csv", "latin-1") # TypeError
A / does the opposite: parameters before it can only be passed by position. Library authors use it so they can rename those parameters later without breaking callers. Many built-in functions already work this way, which is why len(obj=[1, 2]) fails while len([1, 2]) works.
def scale(value, factor, /):
return value * factor
scale(10, 3) # 30
scale(value=10, factor=3) # TypeError
Unpacking Values Into a Call
The star symbols also work at the call site. A single star spreads a list or tuple into positional arguments, and a double star spreads a dictionary into keyword arguments.
def bmi(weight_kg, height_m):
return round(weight_kg / height_m ** 2, 1)
values = [68, 1.72]
person = {"weight_kg": 54, "height_m": 1.6}
print(bmi(*values)) # 23.0
print(bmi(**person)) # 21.1
This pattern is common in data science code, where settings are stored in a dictionary and passed straight into functions such as pd.read_csv(**read_options) or a model constructor.
The Mutable Default Trap
Default values are created once, when the function is defined, not each time it is called. A list or dictionary used as a default is therefore shared between calls.
def add_score(score, scores=[]): # risky
scores.append(score)
return scores
add_score(5) # [5]
add_score(7) # [5, 7] surprise!
def add_score(score, scores=None): # safe
if scores is None:
scores = []
scores.append(score)
return scores
Picking the Right Kind
- Use positional parameters for one or two obvious inputs, such as
xandy. - Use defaults for options most callers will not change.
- Use keyword arguments at the call site whenever a function takes more than two or three values;
train(model, data, epochs=10, lr=0.01)is far easier to read than a row of bare numbers. - Make boolean flags keyword-only so calls read clearly.
- Reach for
*argsand**kwargsmainly in wrappers and helpers that pass values on to other functions. - Avoid catching everything in
**kwargswhen a fixed list of parameters would document the function better. - Read the signature of library functions with
help(function_name); the*and/markers there tell you exactly how each argument may be passed.