Text
stringlengths
1
9.41k
Function attributes can sometimes allow state to be attached to the function itself, instead of looked up in scopes.
Another alternative, using OOP with classes, sometimes supports state retention better than any of the scope-based techniques because it makes it explicit with attribute assignments; we’ll explore this option in Part VI. **|** ----- ###### CHAPTER 18 ### Arguments Chapter 17 explored the details behind Python’s sc...
As we learned, the place where a name is defined in our code determines much of its meaning.
This chapter continues the function story by studying the concepts in Python argument passing—the way that objects are sent to functions as inputs. As we’ll see, arguments (a.k.a.
parameters) are assigned to names in a function, but they have more to do with object references than with variable scopes. We’ll also find that Python provides extra tools, such as keywords, defaults, and arbitrary argument collectors, that allow for wide flexibility in the way arguments are sent to a function. #####...
This has a few ramifications that aren’t always obvious to beginners, which I’ll expand on in this section.
Here is a rundown of the key points in passing arguments to functions: - Arguments are passed by automatically assigning objects to local variable **names.
Function arguments—references to (possibly) shared objects sent by the** caller—are just another instance of Python assignment at work.
Because references are implemented as pointers, all arguments are, in effect, passed by pointer.
Objects passed as arguments are never automatically copied. - Assigning to argument names inside a function does not affect the caller. Argument names in the function header become new, local names when the function runs, in the scope of the function.
There is no aliasing between function argument names and variable names in the scope of the caller. - Changing a mutable object argument in a function may impact the caller. On the other hand, as arguments are simply assigned to passed-in objects, functions can change passed-in mutable objects in place, and the resul...
Mutable arguments can be input and output for functions. ----- For more details on references, see Chapter 6; everything we learned there also applies to function arguments, though the assignment to argument names is automatic and implicit. Python’s pass-by-assignment scheme isn’t quite the same as C++’s reference ...
a = 99` _# Changes local variable a only_ ``` ... >>> b = 88 ``` `>>> f(b)` _# a and b both reference same 88 initially_ `>>> print(b)` _# b is not changed_ ``` 88 ``` In this example the variable a is assigned the object 88 at the moment the function is called with `f(b), but` `a lives only within the called f...
Changing` `a inside the` function has no effect on the place where the function is called; it simply resets the local variable a to a completely different object. That’s what is meant by a lack of name aliasing—assignment to an argument name inside a function (e.g., a=99) does not magically change a variable like b in...
Argument names may share passed objects initially (they are essentially pointers to those objects), but only temporarily, when the function is first called. As soon as an argument name is reassigned, this relationship ends. At least, that’s the case for assignment to argument names themselves.
When arguments are passed mutable objects like lists and dictionaries, we also need to be aware that inplace changes to such objects may live on after a function exits, and hence impact callers. Here’s an example that demonstrates this behavior: **|** ----- `>>> def changer(a, b):` _# Arguments assigned references ...
a = 2` _# Changes local name's value only_ `...
b[0] = 'spam'` _# Changes shared object in-place_ ``` ... >>> X = 1 ``` `>>> L = [1, 2]` _# Caller_ `>>> changer(X, L)` _# Pass immutable and mutable objects_ `>>> X, L` _# X is unchanged, L is different!_ ``` (1, ['spam', 2]) ``` In this code, the changer function assigns values to argument a itself, and to a ...
These two assignments within the function are only slightly different in syntax but have radically different results: - Because a is a local variable name in the function’s scope, the first assignment has no effect on the caller—it simply changes the local variable a to reference a completely different object, and do...
This is the same as in the prior example. - Argument b is a local variable name, too, but it is passed a mutable object (the list that `L references in the caller’s scope).
As the second assignment is an in-place` object change, the result of the assignment to b[0] in the function impacts the value of L after the function returns. Really, the second assignment statement in changer doesn’t change b—it changes part of the object that b currently references.
This in-place change impacts the caller only because the changed object outlives the function call.
The name `L hasn’t changed` either—it still references the same, changed object—but it seems as though L differs after the call because the value it references has been modified within the function. Figure 18-1 illustrates the name/object bindings that exist immediately after the function has been called, and before i...
In terms of the first argument, the assignment has no effect on the caller: ``` >>> X = 1 ``` `>>> a = X` _# They share the same object_ `>>> a = 2` _# Resets 'a' only, 'X' is still 1_ ``` >>> print(X) 1 ``` The assignment through the second argument does affect a variable at the call, though, because it is an ...
References: arguments. Because arguments are passed by assignment, argument names_ _in the function may share objects with variables in the scope of the call.
Hence, in-place changes to_ _mutable arguments in a function can impact the caller.
Here, a and b in the function initially reference_ _the objects referenced by variables X and L when the function is first called.
Changing the list through_ _variable b makes L appear different after the call returns._ If you recall our discussions about shared mutable objects in Chapters 6 and 9, you’ll recognize the phenomenon at work: changing a mutable object in-place can impact other references to that object.
Here, the effect is to make one of the arguments work like both an input and an output of the function. ###### Avoiding Mutable Argument Changes This behavior of in-place changes to mutable arguments isn’t a bug—it’s simply the way argument passing works in Python.
Arguments are passed to functions by reference (a.k.a. pointer) by default because that is what we normally want.
It means we can pass large objects around our programs without making multiple copies along the way, and we can easily update these objects as we go.
In fact, as we’ll see in Part VI, Python’s class model depends upon changing a passed-in “self” argument in-place, to update object state. If we don’t want in-place changes within functions to impact objects we pass to them, though, we can simply make explicit copies of mutable objects, as we learned in Chapter 6.
For function arguments, we can always copy the list at the point of call: ``` L = [1, 2] changer(X, L[:]) # Pass a copy, so our 'L' does not change ``` We can also copy within the function itself, if we never want to change passed-in objects, regardless of how the function is called: ``` def changer(a, b): `...
To really prevent changes, we can always convert to immutable objects to force the issue.
Tuples, for example, throw an exception when changes are attempted: ``` L = [1, 2] changer(X, tuple(L)) # Pass a tuple, so changes are errors ``` This scheme uses the built-in tuple function, which builds a new tuple out of all the items in a sequence (really, any iterable).
It’s also something of an extreme—because it forces the function to be written to never change passed-in arguments, this solution might impose more limitations on the function than it should, and so should generally be avoided (you never know when changing arguments might come in handy for other calls in the future).
Using this technique will also make the function lose the ability to call any list-specific methods on the argument, including methods that do not change the object in-place. The main point to remember here is that functions might update mutable objects like lists and dictionaries passed into them.
This isn’t necessarily a problem if it’s expected, and often serves useful purposes.
Moreover, functions that change passed-in mutable objects in place are probably designed and intended to do so—the change is likely part of a well-defined API that you shouldn’t violate by making copies. However, you do have to be aware of this property—if objects change out from under you unexpectedly, check whether ...
Here’s another way to use this statement: because return can send back any sort of object, it can return multiple values by packaging them in a tuple or other collection type.
In fact, although Python doesn’t support what some languages label “call-by-reference” argument passing, we can usually simulate it by returning tuples and assigning the results back to the original argument names in the caller: ``` >>> def multiple(x, y): ``` `...
x = 2` _# Changes local names only_ ``` ... y = [3, 4] ``` `...
return x, y` _# Return new values in a tuple_ ``` ... >>> X = 1 >>> L = [1, 2] ``` `>>> X, L = multiple(X, L)` _# Assign results to caller's names_ ``` >>> X, L (2, [3, 4]) ``` **|** ----- It looks like the code is returning two values here, but it’s really just one—a two-item tuple with the optional sur...
After the call returns, we can use tuple assignment to unpack the parts of the returned tuple.
(If you’ve forgotten why this works, flip back to “Tuples” on page 225 in Chapter 4, Chapter 9, and “Assignment Statements” on page 279 in Chapter 11.) The net effect of this coding pattern is to simulate the output parameters of other languages by explicit assignments.
`X and` `L` change after the call, but only because the code said so. _Unpacking arguments in Python 2.X: The preceding example unpacks a_ tuple returned by the function with tuple assignment.
In Python 2.6, it’s also possible to automatically unpack tuples in arguments passed to a function.
In 2.6, a function defined by this header: ``` def f((a, (b, c))): ``` can be called with tuples that match the expected structure: ``` f((1, (2, 3))) assigns a, b, and c to 1, 2, and 3, respectively.
Naturally, ``` the passed tuple can also be an object created before the call (f(T)). This ``` def syntax is no longer supported in Python 3.0.
Instead, code this ``` function as: ``` def f(T): (a, (b, c)) = T ``` to unpack in an explicit assignment statement. This explicit form works in both 3.0 and 2.6.
Argument unpacking is an obscure and rarely used feature in Python 2.X.
Moreover, a function header in 2.6 supports only the tuple form of sequence assignment; more general sequence assignments (e.g., def f((a, [b, c])):) fail on syntax errors in 2.6 as well and require the explicit assignment form. Tuple unpacking argument syntax is also disallowed by 3.0 in lambda function argument list...
Somewhat asymmetrically, tuple unpacking assignment is still automatic in 3.0 for loops targets, though; see Chapter 13 for examples. ###### Special Argument-Matching Modes As we’ve just seen, arguments are always passed by assignment in Python; names in the ``` def header are assigned to passed-in objects.
On top of this model, though, Python ``` provides additional tools that alter the way the argument objects in a call are _matched with argument names in the header prior to assignment.
These tools are all_ optional, but they allow us to write functions that support more flexible calling patterns, and you may encounter some libraries that require them. **|** ----- By default, arguments are matched by position, from left to right, and you must pass exactly as many arguments as there are argument na...
In fact, some of these tools are intended more for people writing libraries than for application developers. But because you may stumble across these modes even if you don’t code them yourself, here’s a synopsis of the available tools: _Positionals: matched from left to right_ The normal case, which we’ve mostly been ...
This is the inverse of a * in a function header—in the header it means collect arbitrarily many arguments, while in the call it means pass arbitrarily many arguments. _Keyword-only arguments: arguments that must be passed by name_ In Python 3.0 (but not 2.6), functions can also specify arguments that must be passed by ...
Such arguments are typically used to define configuration options in addition to actual arguments. **|** ----- ###### Matching Syntax Table 18-1 summarizes the syntax that invokes the special argument-matching modes. _Table 18-1.
Function argument-matching forms_ **Syntax** **Location** **Interpretation** `func(value)` Caller Normal argument: matched by position `func(name=value)` Caller Keyword argument: matched by name `func(*sequence)` Caller Pass all objects in sequence as individual positional arguments `func(**dict)` Caller Pass al...
Using a *sequence or **dict in a call allows us to package up arbitrarily many positional or keyword objects in sequences and dictionaries, respectively, and unpack them as separate, individual arguments when they are passed to the function. - In a function header (the rest of the table), a simple name is matched by ...
The *name form collects any extra unmatched positional arguments_ in a tuple, and the **name form collects extra keyword arguments in a dictionary. In Python 3.0 and later, any normal or defaulted argument names following a ``` *name or a bare * are keyword-only arguments and must be passed by keyword in ``` calls. ...
We’ve informally used both of these earlier in this book: - We’ve already used keywords to specify options to the 3.0 print function, but they are more general—keywords allow us to label any argument with its name, to make calls more informational. **|** ----- - We met defaults earlier, too, as a way to pass in ...
If a function specifies defaults, they are used if you pass too few arguments.
If a function uses the * variable argument list forms, you can pass too many arguments; the * names collect the extra arguments in data structures for processing in the function. ###### The Gritty Details If you choose to use and combine the special argument-matching modes, Python will ask you to follow these orderin...
If you mix` arguments in any other order, you will get a syntax error because the combinations can be ambiguous.
The steps that Python internally carries out to match arguments before assignment can roughly be described as follows: 1. Assign nonkeyword arguments by position. 2.
Assign keyword arguments by matching names. 3. Assign extra nonkeyword arguments to *name tuple. 4. Assign extra keyword arguments to **name dictionary. 5.
Assign default values to unassigned arguments in header. After this, Python checks to make sure each argument is passed just one value; if not, an error is raised.
When all matching is complete, Python assigns argument names to the objects passed to them. **|** ----- The actual matching algorithm Python uses is a bit more complex (it must also account for keyword-only arguments in 3.0, for instance), so we’ll defer to Python’s standard language manual for a more exact descrip...
It’s not required reading, but tracing Python’s matching algorithm may help you to understand some convoluted cases, especially when modes are mixed. In Python 3.0, argument names in a function header can also have an_notation values, specified as name:value (or name:value=default when_ defaults are present).
This is simply additional syntax for arguments and does not augment or change the argument-ordering rules described here.
The function itself can also have an annotation value, given as `def f()->value.
See the discussion of function annotation in` Chapter 19 for more details. ###### Keyword and Default Examples This is all simpler in code than the preceding descriptions may imply.
If you don’t use any special matching syntax, Python matches names by position from left to right, like most other languages.
For instance, if you define a function that requires three arguments, you must call it with three arguments: ``` >>> def f(a, b, c): print(a, b, c) ... ``` Here, we pass them by position—a is matched to 1, b is matched to 2, and so on (this works the same in Python 3.0 and 2.6, but extra tuple parentheses are disp...
Keyword arguments allow us to match by name, instead of by position: ``` >>> f(c=3, b=2, a=1) 1 2 3 ``` The c=3 in this call, for example, means send 3 to the argument named c.
More formally, Python matches the name c in the call to the argument named c in the function definition’s header, and then passes the value 3 to that argument.
The net effect of this call is the same as that of the prior call, but notice that the left-to-right order of the arguments no longer matters when keywords are used because arguments are matched by name, not by position.
It’s even possible to combine positional and keyword arguments in a single call.
In this case, all positionals are matched first from left to right in the header, before keywords are matched by name: **|** ----- ``` >>> f(1, c=3, b=2) 1 2 3 ``` When most people see this the first time, they wonder why one would use such a tool. Keywords typically have two roles in Python.
First, they make your calls a bit more selfdocumenting (assuming that you use better argument names than `a,` `b, and` `c).
For` example, a call of this form: ``` func(name='Bob', age=40, job='dev') ``` is much more meaningful than a call with three naked values separated by commas— the keywords serve as labels for the data in the call.
The second major use of keywords occurs in conjunction with defaults, which we turn to next. ###### Defaults We talked about defaults in brief earlier, when discussing nested function scopes.
In short, defaults allow us to make selected function arguments optional; if not passed a value, the argument is assigned its default before the function runs.
For example, here is a function that requires one argument and defaults two: ``` >>> def f(a, b=2, c=3): print(a, b, c) ... ``` When we call this function, we must provide a value for a, either by position or by keyword; however, providing values for b and c is optional.
If we don’t pass values to ``` b and c, they default to 2 and 3, respectively: >>> f(1) 1 2 3 >>> f(a=1) 1 2 3 ``` If we pass two values, only c gets its default, and with three values, no defaults are used: ``` >>> f(1, 4) 1 4 3 >>> f(1, 4, 5) 1 4 5 ``` Finally, here is how the keyword and default fe...
Because they subvert the normal left-to-right positional mapping, keywords allow us to essentially skip over arguments with defaults: ``` >>> f(1, c=6) 1 2 6 ``` Here, a gets 1 by position, c gets 6 by keyword, and b, in between, defaults to 2. Be careful not to confuse the special `name=value syntax in a functio...
In both cases, this is not an assignment statement (despite its appearance); it is special syntax for these two contexts, which modifies the default argument-matching mechanics. **|** ----- ###### Combining keywords and defaults Here is a slightly larger example that demonstrates keywords and defaults in action.
In the following, the caller must always pass at least two arguments (to match spam and ``` eggs), but the other two are optional.
If they are omitted, Python assigns toast and ham to the defaults specified in the header: def func(spam, eggs, toast=0, ham=0): # First 2 required print((spam, eggs, toast, ham)) func(1, 2) # Output: (1, 2, 0, 0) func(1, ham=1, eggs=0) # Output: (1, 0, 0, 1) func(spam=1, eggs=0) ...
The caller must supply values for spam and eggs, but they can be matched by position or by name.
Again, keep in mind that the form name=value means different things in the call and the def: a keyword in the call and a default in the header. ###### Arbitrary Arguments Examples The last two matching extensions, * and **, are designed to support functions that take any number of arguments.
Both can appear in either the function definition or a function call, and they have related purposes in the two locations. ###### Collecting arguments The first use, in the function definition, collects unmatched positional arguments into a tuple: ``` >>> def f(*args): print(args) ... ``` When this function is c...
Because it is a normal tuple object, it can be indexed, stepped through with a for loop, and so on: ``` >>> f() () >>> f(1) (1,) >>> f(1, 2, 3, 4) (1, 2, 3, 4) ``` The ** feature is similar, but it only works for keyword arguments—it collects them into a new dictionary, which can then be processed with nor...
In a sense, the ** form allows you to convert from keywords to dictionaries, which you can then step through with keys calls, dictionary iterators, and the like: **|** ----- ``` >>> def f(**args): print(args) ... >>> f() {} >>> f(a=1, b=2) {'a': 1, 'b': 2} ``` Finally, function headers can combine norm...
For instance, in the following, 1 is passed to a by position, 2 and 3 are collected into the pargs positional tuple, and x and y wind up in the kargs keyword dictionary: ``` >>> def f(a, *pargs, **kargs): print(a, pargs, kargs) ... >>> f(1, 2, 3, x=1, y=2) 1 (2, 3) {'y': 2, 'x': 1} ``` In fact, these features ...
First, though, let’s see what happens when * and ** are coded in function calls instead of definitions. ###### Unpacking arguments In recent Python releases, we can use the * syntax when we call a function, too.
In this context, its meaning is the inverse of its meaning in the function definition—it unpacks a collection of arguments, rather than building a collection of arguments.
For example, we can pass four arguments to a function in a tuple and let Python unpack them into individual arguments: ``` >>> def func(a, b, c, d): print(a, b, c, d) ... >>> args = (1, 2) >>> args += (3, 4) >>> func(*args) 1 2 3 4 ``` Similarly, the ** syntax in a function call unpacks a dictionary of key...
Again, don’t confuse the */** syntax in the function header and the function call—in the header it collects any number of arguments, while in the call it unpacks any number of arguments. As we saw in Chapter 14, the *pargs form in a call is an iteration con_text, so technically it accepts any iterable object, not just...