Many edits

This commit is contained in:
David Beazley
2020-05-28 17:41:59 -05:00
parent 9572f707b2
commit a83a9cf064
23 changed files with 467 additions and 210 deletions

View File

@@ -1,25 +1,31 @@
[Contents](../Contents) \| [Previous (6.4 Generator Expressions)](../06_Generators/04_More_generators) \| [Next (7.2 Anonymous Functions)](02_Anonymous_function)
# 7.1 Variable Arguments
This section covers variadic function arguments, sometimes described as
`*args` and `**kwargs`.
### Positional variable arguments (*args)
A function that accepts *any number* of arguments is said to use variable arguments.
For example:
```python
def foo(x, *args):
def f(x, *args):
...
```
Function call.
```python
foo(1,2,3,4,5)
f(1,2,3,4,5)
```
The arguments get passed as a tuple.
The extra arguments get passed as a tuple.
```python
def foo(x, *args):
def f(x, *args):
# x -> 1
# args -> (2,3,4,5)
```
@@ -30,37 +36,52 @@ A function can also accept any number of keyword arguments.
For example:
```python
def foo(x, y, **kwargs):
def f(x, y, **kwargs):
...
```
Function call.
```python
foo(2,3,flag=True,mode='fast',header='debug')
f(2, 3, flag=True, mode='fast', header='debug')
```
The extra keywords are passed in a dictionary.
```python
def foo(x, y, **kwargs):
def f(x, y, **kwargs):
# x -> 2
# y -> 3
# kwargs -> { 'flat': True, 'mode': 'fast', 'header': 'debug' }
# kwargs -> { 'flag': True, 'mode': 'fast', 'header': 'debug' }
```
### Combining both
A function can also combine any number of variable keyword and non-keyword arguments.
Function definition.
A function can also accept any number of variable keyword and non-keyword arguments.
```python
def foo(*args, **kwargs):
def f(*args, **kwargs):
...
```
This function takes any combination of positional or keyword arguments.
It is sometimes used when writing wrappers or when you want to pass arguments through to another function.
Function call.
```python
f(2, 3, flag=True, mode='fast', header='debug')
```
The arguments are separated into positional and keyword components
```python
def f(*args, **kwargs):
# args = (2, 3)
# kwargs -> { 'flag': True, 'mode': 'fast', 'header': 'debug' }
...
```
This function takes any combination of positional or keyword
arguments. It is sometimes used when writing wrappers or when you
want to pass arguments through to another function.
### Passing Tuples and Dicts
@@ -68,7 +89,7 @@ Tuples can be expanded into variable arguments.
```python
numbers = (2,3,4)
foo(1, *numbers) # Same as f(1,2,3,4)
f(1, *numbers) # Same as f(1,2,3,4)
```
Dictionaries can also be expaded into keyword arguments.
@@ -79,12 +100,10 @@ options = {
'delimiter' : ',',
'width' : 400
}
foo(data, **options)
# Same as foo(data, color='red', delimiter=',', width=400)
f(data, **options)
# Same as f(data, color='red', delimiter=',', width=400)
```
These are not commonly used except when writing library functions.
## Exercises
### Exercise 7.1: A simple example of variable arguments