---
# System prepended metadata

title: Arguments
tags: [Python]

---

---
tags: Python
---
# Arguments

## *args

> The ***args** will give you all function parameters as a tuple.

> The special syntax ***args** in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-keyworded, variable-length argument list.

## **kwargs

> The special syntax ****kwargs** in function definitions in python is used to pass a keyworded, variable-length argument list.

## Special parameters

先來個懶人包：

```python
def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
      -----------    ----------     ----------
        |             |                  |
        |        Positional or keyword   |
        |                                - Keyword only
         -- Positional only
```

### Positional-only Arguments

`/` 前面的 argument 必須要以 positional 的方式給，否則會跳 `TypeError` 。

```python
def func(a, /, b):
    print(a, b)

>>> func(1, 2)
1 2

>>> func(a=1, b=2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    func(a=1, b=2)
TypeError: func() got some positional-only arguments passed as keyword arguments: 'a'
```

### Keyword-Only Arguments

`*` 後面的 argument 必須要以給 key 的方式執行，否則會跳 `TypeError`。

```python
def func(a, *, b=None):
    print(a, b)
    
>>> compare(1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: compare() takes 1 positional arguments but 2 were given

>>> compare(1, b=2)
1 2
```

## 參考資料

 - [More Control Flow Tools / Python](https://docs.python.org/dev/tutorial/controlflow.html#more-on-defining-functions)
 - [PEP 3102 -- Keyword-Only Arguments](https://www.python.org/dev/peps/pep-3102/)