• No results found

More on Defining Functions

In document and the Python development team (Page 30-35)

It is also possible to define functions with a variable number of arguments. There are three forms, which can be combined.

4.7.1 Default Argument Values

The most useful form is to specify a default value for one or more arguments. This creates a function that can be called with fewer arguments than it is defined to allow. For example:

def ask_ok(prompt, retries=4, reminder='Please try again!'):

while True:

ok = input(prompt)

if ok in ('y', 'ye', 'yes'):

return True

if ok in ('n', 'no', 'nop', 'nope'):

return False retries = retries - 1 if retries < 0:

raise ValueError('invalid user response') print(reminder)

This function can be called in several ways:

• giving only the mandatory argument: ask_ok('Do you really want to quit?')

• giving one of the optional arguments: ask_ok('OK to overwrite the file?', 2)

• or even giving all arguments: ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')

This example also introduces theinkeyword. This tests whether or not a sequence contains a certain value.

The default values are evaluated at the point of function definition in thedefining scope, so that

i = 5

def f(arg=i):

print(arg) i = 6

f()

will print5.

Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:

def f(a, L=[]):

L.append(a) return L

Python Tutorial, Release 3.6.4

print(f(1)) print(f(2)) print(f(3))

This will print [1]

[1, 2]

[1, 2, 3]

If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:

def f(a, L=None):

if L is None:

L = []

L.append(a) return L

4.7.2 Keyword Arguments

Functions can also be called usingkeyword argumentsof the formkwarg=value. For instance, the following function:

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):

print("-- This parrot wouldn't", action, end=' ') print("if you put", voltage, "volts through it.") print("-- Lovely plumage, the", type)

print("-- It's", state, "!")

accepts one required argument (voltage) and three optional arguments (state, action, and type). This function can be called in any of the following ways:

parrot(1000) # 1 positional argument

parrot(voltage=1000) # 1 keyword argument

parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments parrot('a million', 'bereft of life', 'jump') # 3 positional arguments parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword but all the following calls would be invalid:

parrot() # required argument missing

parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument parrot(110, voltage=220) # duplicate value for the same argument

parrot(actor='John Cleese') # unknown keyword argument

In a function call, keyword arguments must follow positional arguments. All the keyword arguments passed must match one of the arguments accepted by the function (e.g. actor is not a valid argument for theparrotfunction), and their order is not important. This also includes non-optional arguments (e.g.

parrot(voltage=1000)is valid too). No argument may receive a value more than once. Here’s an example that fails due to this restriction:

>>> def function(a):

... pass

...

4.7. More on Defining Functions 25

>>> function(0, a=0)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: function() got multiple values for keyword argument 'a'

When a final formal parameter of the form **name is present, it receives a dictionary (see typesmapping) containing all keyword arguments except for those corresponding to a formal parameter. This may be combined with a formal parameter of the form *name (described in the next subsection) which receives a tuple containing the positional arguments beyond the formal parameter list. (*name must occur before

**name.) For example, if we define a function like this:

def cheeseshop(kind, *arguments, **keywords):

print("-- Do you have any", kind, "?") print("-- I'm sorry, we're all out of", kind) for arg in arguments:

print(arg) print("-" * 40) for kw in keywords:

print(kw, ":", keywords[kw])

It could be called like this:

cheeseshop("Limburger", "It's very runny, sir.",

"It's really very, VERY runny, sir.", shopkeeper="Michael Palin",

client="John Cleese", sketch="Cheese Shop Sketch") and of course it would print:

-- Do you have any Limburger ?

-- I'm sorry, we're all out of Limburger It's very runny, sir.

It's really very, VERY runny, sir.

---shopkeeper : Michael Palin

client : John Cleese sketch : Cheese Shop Sketch

Note that the order in which the keyword arguments are printed is guaranteed to match the order in which they were provided in the function call.

4.7.3 Arbitrary Argument Lists

Finally, the least frequently used option is to specify that a function can be called with an arbitrary number of arguments. These arguments will be wrapped up in a tuple (see Tuples and Sequences). Before the variable number of arguments, zero or more normal arguments may occur.

def write_multiple_items(file, separator, *args):

file.write(separator.join(args))

Normally, these variadic arguments will be last in the list of formal parameters, because they scoop up all remaining input arguments that are passed to the function. Any formal parameters which occur after the*argsparameter are ‘keyword-only’ arguments, meaning that they can only be used as keywords rather than positional arguments.

Python Tutorial, Release 3.6.4

>>> def concat(*args, sep="/"):

... return sep.join(args) ...

>>> concat("earth", "mars", "venus")

'earth/mars/venus'

>>> concat("earth", "mars", "venus", sep=".")

'earth.mars.venus'

4.7.4 Unpacking Argument Lists

The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments. For instance, the built-inrange()function expects separate start and stop arguments. If they are not available separately, write the function call with the

*-operator to unpack the arguments out of a list or tuple:

>>> list(range(3, 6)) # normal call with separate arguments

[3, 4, 5]

>>> args = [3, 6]

>>> list(range(*args)) # call with arguments unpacked from a list

[3, 4, 5]

In the same fashion, dictionaries can deliver keyword arguments with the**-operator:

>>> def parrot(voltage, state='a stiff', action='voom'):

... print("-- This parrot wouldn't", action, end=' ')

... print("if you put", voltage, "volts through it.", end=' ') ... print("E's", state, "!")

...

>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}

>>> parrot(**d)

-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

4.7.5 Lambda Expressions

Small anonymous functions can be created with thelambdakeyword. This function returns the sum of its two arguments: lambda a, b: a+b. Lambda functions can be used wherever function objects are required.

They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda functions can reference variables from the containing scope:

>>> def make_incrementor(n):

... return lambda x: x + n ...

>>> f = make_incrementor(42)

>>> f(0) 42

>>> f(1) 43

The above example uses a lambda expression to return a function. Another use is to pass a small function as an argument:

>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]

>>> pairs.sort(key=lambda pair: pair[1])

4.7. More on Defining Functions 27

>>> pairs

[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

4.7.6 Documentation Strings

Here are some conventions about the content and formatting of documentation strings.

The first line should always be a short, concise summary of the object’s purpose. For brevity, it should not explicitly state the object’s name or type, since these are available by other means (except if the name happens to be a verb describing a function’s operation). This line should begin with a capital letter and end with a period.

If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description. The following lines should be one or more paragraphs describing the object’s calling conventions, its side effects, etc.

The Python parser does not strip indentation from multi-line string literals in Python, so tools that process documentation have to strip indentation if desired. This is done using the following convention. The first non-blank line after the first line of the string determines the amount of indentation for the entire documentation string. (We can’t use the first line since it is generally adjacent to the string’s opening quotes so its indentation is not apparent in the string literal.) Whitespace “equivalent” to this indentation is then stripped from the start of all lines of the string. Lines that are indented less should not occur, but if they occur all their leading whitespace should be stripped. Equivalence of whitespace should be tested after expansion of tabs (to 8 spaces, normally).

Here is an example of a multi-line docstring:

>>> def my_function():

... """Do nothing, but document it.

...

... No, really, it doesn't do anything.

... """

... pass

...

>>> print(my_function.__doc__)

Do nothing, but document it.

No, really, it doesn't do anything.

4.7.7 Function Annotations

Function annotations are completely optional metadata information about the types used by user-defined functions (seePEP 484 for more information).

Annotations are stored in the__annotations__attribute of the function as a dictionary and have no effect on any other part of the function. Parameter annotations are defined by a colon after the parameter name, followed by an expression evaluating to the value of the annotation. Return annotations are defined by a literal->, followed by an expression, between the parameter list and the colon denoting the end of thedef statement. The following example has a positional argument, a keyword argument, and the return value annotated:

>>> def f(ham: str, eggs: str = 'eggs') -> str:

... print("Annotations:", f.__annotations__) ... print("Arguments:", ham, eggs)

... return ham + ' and ' + eggs ...

Python Tutorial, Release 3.6.4

>>> f('spam')

Annotations: {'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>}

Arguments: spam eggs 'spam and eggs'

In document and the Python development team (Page 30-35)