Text stringlengths 1 9.41k |
|---|
For instance, a file object
works after the *, and unpacks its lines into individual arguments (e.g.,
```
func(*open('fname')).
```
This generality is supported in both Python 3.0 and 2.6, but it holds true
only for calls—a *pargs in a call allows any iterable, but the same form
in a def header always bundles e... |
This header
behavior is similar in spirit and syntax to the * in Python 3.0 extended
sequence unpacking assignment forms we met in Chapter 11 (e.g., x,
```
*y = z), though that feature always creates lists, not tuples.
###### Applying functions generically
```
The prior section’s examples may seem obtuse, but ... |
Some programs need to call arbitrary functions in a generic fashion,
without knowing their names or arguments ahead of time. |
In fact, the real power of
the special “varargs” call syntax is that you don’t need to know how many arguments
a function call requires before you write a script. |
For example, you can use if logic to
select from a set of functions and argument lists, and call any of them generically:
```
if <test>:
action, args = func1, (1,) # Call func1 with 1 arg in this case
else:
action, args = func2, (1, 2, 3) # Call func2 with 3 args here
...
action(*args) ... |
If your user selects an arbitrary function via a user interface, for instance,
you may be unable to hardcode a function call when writing your script. |
To work
around this, simply build up the arguments list with sequence operations, and call it
with starred names to unpack the arguments:
**|**
-----
```
>>> args = (2,3)
>>> args += (4,)
>>> args
(2, 3, 4)
>>> func(*args)
```
Because the arguments list is passed in as a tuple here, the program can build... |
This technique also comes in handy for functions that test or time other functions. |
For instance, in the following code we support any function with any arguments
by passing along whatever arguments were sent in:
```
def tracer(func, *pargs, **kargs): # Accept arbitrary arguments
print('calling:', func.__name__)
return func(*pargs, **kargs) # Pass along arbitrary arguments
def fun... |
This original technique has been removed in 3.0 because it is now redundant (3.0 cleans up many such dusty tools that
have been subsumed over the years). |
It’s still available in Python 2.6, though, and you
may come across it in older 2.X code.
In short, the following are equivalent prior to Python 3.0:
`func(*pargs, **kargs)` _# Newer call syntax: func(*sequence, **dict)_
`apply(func, pargs, kargs)` _# Defunct built-in: apply(func, sequence, dict)_
For example, cons... |
Apart from its symmetry with the *pargs and **kargs collector
forms in def headers, and the fact that it requires fewer keystrokes overall, the newer
call syntax also allows us to pass along additional arguments without having to manually extend argument sequences or dictionaries:
```
>>> echo(0, c=5, *pargs, **kargs... |
Since it’s required in 3.0, you should now
disavow all knowledge of apply (unless, of course, it appears in 2.X code you must use
or maintain...).
###### Python 3.0 Keyword-Only Arguments
Python 3.0 generalizes the ordering rules in function headers to allow us to specify
_keyword-only arguments—arguments that must b... |
This is useful if we want a function to both
process any number of arguments and accept possibly optional configuration options.
Syntactically, keyword-only arguments are coded as named arguments that appear after
```
*args in the arguments list. |
All such arguments must be passed using keyword syntax
```
in the call. |
For example, in the following, a may be passed by name or position, b collects
any extra positional arguments, and c must be passed by keyword only:
```
>>> def kwonly(a, *b, c):
... |
print(a, b, c)
...
>>> kwonly(1, 2, c=3)
1 (2,) 3
>>> kwonly(a=1, c=3)
1 () 3
>>> kwonly(1, 2, 3)
TypeError: kwonly() needs keyword-only argument c
```
We can also use a * character by itself in the arguments list to indicate that a function
does not accept a variable-length argument list but still expec... |
In the next function, a may be passed by position or
name again, but b and c must be keywords, and no extra positionals are allowed:
**|**
-----
```
>>> def kwonly(a, *, b, c):
... |
print(a, b, c)
...
>>> kwonly(1, c=3, b=2)
1 2 3
>>> kwonly(c=3, b=2, a=1)
1 2 3
>>> kwonly(1, 2, 3)
TypeError: kwonly() takes exactly 1 positional argument (3 given)
>>> kwonly(1)
TypeError: kwonly() needs keyword-only argument b
```
You can still use defaults for keyword-only arguments, even though... |
In the following code, a may be passed by name or position,
and b and c are optional but must be passed by keyword if used:
```
>>> def kwonly(a, *, b='spam', c='ham'):
... |
print(a, b, c)
...
>>> kwonly(1)
1 spam ham
>>> kwonly(1, c=3)
1 spam 3
>>> kwonly(a=1)
1 spam ham
>>> kwonly(c=3, b=2, a=1)
1 2 3
>>> kwonly(1, 2)
TypeError: kwonly() takes exactly 1 positional argument (2 given)
```
In fact, keyword-only arguments with defaults are optional, but those without d... |
print(a, b, c)
...
>>> kwonly(1, b='eggs')
1 eggs spam
>>> kwonly(1, c='eggs')
TypeError: kwonly() needs keyword-only argument b
>>> kwonly(1, 2)
TypeError: kwonly() takes exactly 1 positional argument (2 given)
>>> def kwonly(a, *, b=1, c, d=2):
... |
print(a, b, c, d)
...
>>> kwonly(3, c=4)
3 1 4 2
>>> kwonly(3, c=4, b=5)
3 5 4 2
>>> kwonly(3)
TypeError: kwonly() needs keyword-only argument c
>>> kwonly(1, 2, 3)
TypeError: kwonly() takes exactly 1 positional argument (3 given)
```
**|**
-----
###### Ordering rules
Finally, note that keyword-o... |
Both attempts generate a syntax error:
```
>>> def kwonly(a, **pargs, b, c):
SyntaxError: invalid syntax
>>> def kwonly(a, **, b, c):
SyntaxError: invalid syntax
```
This means that in a function header, keyword-only arguments must be coded before
the **args arbitrary keywords form and after the *args arbitrar... |
Whenever an argument name appears before *args, it is a possibly
default positional argument, not keyword-only:
`>>> def f(a, *b, **d, c=6): print(a, b, c, d)` _# Keyword-only before **!_
```
SyntaxError: invalid syntax
```
`>>> def f(a, *b, c=6, **d): print(a, b, c, d)` _# Collect args in header_
```
...
```
`>... |
The keyword-only argument can
be coded either before or after the *args, though, and may be included in **args:
`>>> def f(a, *b, c=6, **d): print(a, b, c, d)` _# KW-only between * and **_
```
...
```
`>>> f(1, *(2, 3), **dict(x=4, y=5))` _# Unpack args at call_
```
1 (2, 3) 6 {'y': 5, 'x': 4}
```
`>>> f(1, *(2,... |
They may appear to be worst cases in the
artificial examples here, but they can come up in real practice, especially for people
who write libraries and tools for other Python programmers to use.
###### Why keyword-only arguments?
So why care about keyword-only arguments? |
In short, they make it easier to allow a
function to accept both any number of positional arguments to be processed, and configuration options passed as keywords. |
While their use is optional, without keywordonly arguments extra work may be required to provide defaults for such options and
to verify that no superfluous keywords were passed.
Imagine a function that processes a set of passed-in objects and allows a tracing flag to
be passed:
```
process(X, Y, Z) # use f... |
The
following guarantees that no positional argument will be incorrectly matched against
```
notify and requires that it be a keyword if passed:
def process(*args, notify=False): ...
```
Since we’re going to see a more realistic example of this later in this chapter, in “Emulating the Python 3.0 print Function” on p... |
For an additional example of keyword-only arguments in action, see the
iteration options timing case study in Chapter 20. |
And for additional function definition
enhancements in Python 3.0, stay tuned for the discussion of function annotation syntax in Chapter 19.
###### The min Wakeup Call!
Time for something more realistic. |
To make this chapter’s concepts more concrete,
let’s work through an exercise that demonstrates a practical application of argumentmatching tools.
Suppose you want to code a function that is able to compute the minimum value from
an arbitrary set of arguments and an arbitrary set of object data types. |
That is, the
function should accept zero or more arguments, as many as you wish to pass. |
Moreover,
the function should work for all kinds of Python object types: numbers, strings, lists,
lists of dictionaries, files, and even None.
The first requirement provides a natural example of how the * feature can be put to
good use—we can collect arguments into a tuple and step over each of them in turn
with a sim... |
The second part of the problem definition is easy: because every
**|**
-----
object type supports comparisons, we don’t have to specialize the function per type (an
application of polymorphism); we can simply compare objects blindly and let Python
worry about what sort of comparison to perform.
###### Full Credit
... |
The Python `sort routine is coded in C and uses a highly optimized`
algorithm that attempts to take advantage of partial ordering in the items to be sorted. |
It’s named “timsort”
after Tim Peters, its creator, and in its documentation it claims to have “supernatural performance” at times
(pretty good, for a sort!). |
Still, sorting is an inherently exponential operation (it must chop up the sequence
and put it back together many times), and the other versions simply perform one linear left-to-right scan.
The net effect is that sorting is quicker if the arguments are partially ordered, but is likely to be slower
otherwise. |
Even so, Python performance can change over time, and the fact that sorting is implemented in
the C language can help greatly; for an exact analysis, you should time the alternatives with the `time or`
```
timeit modules we’ll meet in Chapter 20.
```
**|**
-----
```
print(min2("bb", "aa"))
print(min3([2,2], [1... |
Try typing a few calls
interactively to experiment with these on your own:
```
% python mins.py
1
aa
[1, 1]
```
Notice that none of these three variants tests for the case where no arguments are passed
in. |
They could, but there’s no point in doing so here—in all three solutions, Python
will automatically raise an exception if no arguments are passed in. |
The first variant
raises an exception when we try to fetch item 0, the second when Python detects an
argument list mismatch, and the third when we try to return item 0 at the end.
This is exactly what we want to happen—because these functions support any data
type, there is no valid sentinel value that we could pass b... |
There
are exceptions to this rule (e.g., if you have to run expensive actions before you reach
the error), but in general it’s better to assume that arguments will work in your functions’ code and let Python raise errors for you when they do not.
###### Bonus Points
You can get can get bonus points here for changing ... |
This one’s easy: the first two versions only_
require changing < to >, and the third simply requires that we return tmp[−1] instead of
```
tmp[0]. |
For an extra point, be sure to set the function name to “max” as well (though
```
this part is strictly optional).
It’s also possible to generalize a single function to compute either a minimum _or a_
maximum value, by evaluating comparison expression strings with a tool like the
```
eval built-in function (see the l... |
The file minmax.py shows how to implement the latter scheme:
```
def minmax(test, *args):
res = args[0]
for arg in args[1:]:
if test(arg, res):
res = arg
return res
def lessthan(x, y): return x < y # See also: lambda
def grtrthan(x, y): return x > y
print(minmax(lessthan, 4, 2, ... |
This may seem like extra work, but the main point of generalizing
functions this way (instead of cutting and pasting to change just a single character) is
that we’ll only have one version to change in the future, not two.
###### The Punch Line...
Of course, all this was just a coding exercise. |
There’s really no reason to code min or
`max functions, because both are built-ins in Python! |
We met them briefly in` Chapter 5 in conjunction with numeric tools, and again in Chapter 14 when exploring iteration contexts. |
The built-in versions work almost exactly like ours, but they’re coded
in C for optimal speed and accept either a single iterable or multiple arguments. |
Still,
though it’s superfluous in this context, the general coding pattern we used here might
be useful in other scenarios.
###### Generalized Set Functions
Let’s look at a more useful example of special argument-matching modes at work. |
At
the end of Chapter 16, we wrote a function that returned the intersection of two sequences (it picked out items that appeared in both). |
Here is a version that intersects an
arbitrary number of sequences (one or more) by using the varargs matching form
```
*args to collect all the passed-in arguments. |
Because the arguments come in as a tuple,
```
we can process them in a simple for loop. |
Just for fun, we’ll code a union function that
also accepts an arbitrary number of arguments to collect items that appear in any of
the operands:
```
def intersect(*args):
res = []
for x in args[0]: # Scan first sequence
for other in args[1:]: # For all other args
if x not in other: ... |
In both functions, the arguments passed in at the call come in as the args
tuple. As in the original intersect, both work on any kind of sequence. |
Here, they are
processing strings, mixed types, and more than two sequences:
```
% python
>>> from inter2 import intersect, union
>>> s1, s2, s3 = "SPAM", "SCAM", "SLAM"
```
`>>> intersect(s1, s2), union(s1, s2)` _# Two operands_
```
(['S', 'A', 'M'], ['S', 'P', 'A', 'M', 'C'])
```
`>>> intersect([1,2,3], (1,... |
Because it’s constantly improving, Python has an
uncanny way of conspiring to make my book examples obsolete over
time!
###### Emulating the Python 3.0 print Function
To round out the chapter, let’s look at one last example of argument matching at work.
The code you’ll see here is intended for use in Python 2.6 or ea... |
Here is a test script, testprint30.py (notice that the function must be
```
called “print30”, because “print” is a reserved word in 2.6):
```
from print30 import print30
print30(1, 2, 3)
print30(1, 2, 3, sep='') # Suppress separator
print30(1, 2, 3, sep='...')
print30(1, [2], (3,), sep='...') ... |
As usual, the generality of Python’s design allows us to prototype or develop concepts in the Python
language itself. |
In this case, argument-matching tools are as flexible in Python code as
they are in Python’s internal implementation.
**|**
-----
###### Using Keyword-Only Arguments
It’s interesting to notice that this example could be coded with Python 3.0
keyword-only arguments, described earlier in this chapter, to automatical... |
The original version assumes that all positional
arguments are to be printed, and all keywords are for options only. That’s almost sufficient, but any extra keyword arguments are silently ignored. |
A call like the following,
for instance, will generate an exception with the keyword-only form:
```
>>> print30(99, name='bob')
TypeError: print30() got an unexpected keyword argument 'name'
```
but will silently ignore the name argument in the original version. |
To detect superfluous
keywords manually, we could use dict.pop() to delete fetched entries, and check if the
dictionary is not empty. |
Here is an equivalent to the keyword-only version:
_# Use keyword args deletion with defaults_
```
def print30(*args, **kargs):
sep = kargs.pop('sep', ' ')
end = kargs.pop('end', '\n')
file = kargs.pop('file', sys.stdout)
if kargs: raise TypeError('extra keywords: %s' % kargs)
output = ''
fir... |
Unfortunately, the extra code is required in this
case—the keyword-only version only works on 3.0, which negates most of the reason
that I wrote this example in the first place (a 3.0 emulator that only works on 3.0 isn’t
incredibly useful!). |
In programs written to run on 3.0, though, keyword-only arguments
can simplify a specific category of functions that accept both arguments and options.
For another example of 3.0 keyword-only arguments, be sure to see the upcoming
iteration timing case study in Chapter 20.
###### Why You Will Care: Keyword Arguments
... |
They
are also entirely optional; you can get by with just simple positional matching, and it’s
probably a good idea to do so when you’re starting out. |
However, because some Python
tools make use of them, some general knowledge of these modes is important.
For example, keyword arguments play an important role in tkinter, the de facto standard GUI API for Python (this module’s name is Tkinter in Python 2.6). |
We touch on
```
tkinter only briefly at various points in this book, but in terms of its call patterns,
```
keyword arguments set configuration options when GUI components are built. |
For
instance, a call of the form:
```
from tkinter import *
widget = Button(text="Press me", command=someFunction)
```
creates a new button and specifies its text and callback function, using the text and
```
command keyword arguments. |
Since the number of configuration options for a widget
```
can be large, keyword arguments let you pick and choose which to apply. |
Without
them, you might have to either list all the possible options by position or hope for a
judicious positional argument defaults protocol that would handle every possible option arrangement.
Many built-in functions in Python expect us to use keywords for usage-mode options
as well, which may or may not have defau... |
As we learned in Chapter 8, for instance,
the sorted built-in:
```
sorted(iterable, key=None, reverse=False)
```
expects us to pass an iterable object to be sorted, but also allows us to pass in optional
keyword arguments to specify a dictionary sort key and a reversal flag, which default
to None and False, respec... |
Since we normally don’t use these options, they may
be omitted to use defaults.
###### Chapter Summary
In this chapter, we studied the second of two key concepts related to functions: argu_ments (how objects are passed into a function). |
As we learned, arguments are passed_
into a function by assignment, which means by object reference, which really means
**|**
-----
by pointer. |
We also studied some more advanced extensions, including default and
keyword arguments, tools for using arbitrarily many arguments, and keyword-only
arguments in 3.0. |
Finally, we saw how mutable arguments can exhibit the same behavior as other shared references to objects—unless the object is explicitly copied when
it’s sent in, changing a passed-in mutable in a function can impact the caller.
The next chapter continues our look at functions by exploring some more advanced
function... |
Many of these concepts stem from the fact that functions are normal
```
objects in Python, and so support some advanced and very flexible processing modes.
Before diving into those topics, however, take this chapter’s quiz to review the argument
ideas we’ve studied here.
###### Test Your Knowledge: Quiz
1. |
What is the output of the following code, and why?
```
>>> def func(a, b=4, c=5):
... print(a, b, c)
...
>>> func(1, 2)
```
2. |
What is the output of this code, and why?
```
>>> def func(a, b, c=5):
... print(a, b, c)
...
>>> func(1, c=3, b=2)
```
3. |
How about this code: what is its output, and why?
```
>>> def func(a, *pargs):
... print(a, pargs)
...
>>> func(1, 2, 3)
```
4. |
What does this code print, and why?
```
>>> def func(a, **kargs):
... print(a, kargs)
...
>>> func(a=1, c=3, b=2)
```
5. |
One last time: what is the output of this code, and why?
```
>>> def func(a, b, c=3, d=4): print(a, b, c, d)
...
>>> func(1, *(5,6))
```
6. |
Name three or more ways that functions can communicate results to a caller.
**|**
-----
###### Test Your Knowledge: Answers
1. |
The output here is '1 2 5', because 1 and 2 are passed to a and b by position, and
```
c is omitted in the call and defaults to 5.
```
2. |
The output this time is '1 2 3': 1 is passed to a by position, and b and c are passed
```
2 and 3 by name (the left-to-right order doesn’t matter when keyword arguments
```
are used like this).
3. |
This code prints '1 (2, 3)', because 1 is passed to a and the *pargs collects the
remaining positional arguments into a new tuple object. |
We can step through the
extra positional arguments tuple with any iteration tool (e.g., `for arg in`
```
pargs: ...).
```
4. |
This time the code prints '1, {'c': 3, 'b': 2}', because 1 is passed to a by name
and the **kargs collects the remaining keyword arguments into a dictionary. |
We
could step through the extra keyword arguments dictionary by key with any iteration tool (e.g., for key in kargs: ...).
5. |
The output here is '1 5 6 4': 1 matches a by position, 5 and 6 match b and c by
```
*name positionals (6 overrides c’s default), and d defaults to 4 because it was not
```
passed a value.
6. |
Functions can send back results with `return statements, by changing passed-in`
mutable arguments, and by setting global variables. |
Globals are generally frowned
upon (except for very special cases, like multithreaded programs) because they can
make code more difficult to understand and use. |
`return statements are usually`
best, but changing mutables is fine, if expected. |
Functions may also communicate
with system devices such as files and sockets, but these are beyond our scope here.
**|**
-----
###### CHAPTER 19
### Advanced Function Topics
This chapter introduces a collection of more advanced function-related topics: recursive functions, function attributes and annotations, the ... |
These are all somewhat advanced
tools that, depending on your job description, you may not encounter on a regular
basis. |
Because of their roles in some domains, though, a basic understanding can be
useful; lambdas, for instance, are regular customers in GUIs.
Part of the art of using functions lies in the interfaces between them, so we will also
explore some general function design principles here. |
The next chapter continues this
advanced theme with an exploration of generator functions and expressions and a revival of list comprehensions in the context of the functional tools we will study here.
###### Function Design Concepts
Now that we’ve had a chance to study function basics in Python, let’s begin this cha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.