Parameter and Argument

A parameter is a name in a function definition; an argument is the value supplied at the call. In def label(total, threshold=1000), total and threshold are parameters, and in label(500, threshold=100) the values 500 and 100 are arguments. Inside the body a parameter behaves like any local name.

Arguments match parameters by position unless they are named. A keyword argument, threshold=100, states which parameter it fills, so the order among keyword arguments stops mattering and the call documents itself. Positional arguments must come before keyword arguments. A parameter with a default may be omitted, and omitting a required one raises TypeError that names the missing parameter; passing too many raises TypeError as well.

Defaults are evaluated once, when the def statement runs, not at each call. A mutable default such as def collect(item, target=[]) is shared by calls that omit the argument; if the body appends to that list, later calls see those items, which looks like the function remembering things it should not. Use None as the default and create the list inside the body. Text, numbers, and None avoid this in-place mutation problem, though a computed default is still evaluated at definition time.

Two further forms appear in real code. *args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dictionary; both are conveniences for wrappers rather than a first choice. Arguments are passed by assigning the object to the parameter name, so rebinding a parameter inside the function does not affect the caller, while mutating a list or dictionary that was passed in does.

References: More on defining functions, Why are default values shared between objects. See it in use in Python Functions, Modules, and Classes.


Discover more from Insightful Data Lab

Subscribe to get the latest posts sent to your email.

Similar Posts

Questions, corrections, or additional insights?

This site uses Akismet to reduce spam. Learn how your comment data is processed.