Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

describe lists as default values #36

Merged
merged 8 commits into from
Oct 6, 2022
Merged
96 changes: 96 additions & 0 deletions docs/base/functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,102 @@ Happy Birthday, Mark

Это один из общепринятых способов написания [docstring](https://www.python.org/dev/peps/pep-0257/) — документации по функции.

### Списки как значения по умолчанию

Рассмотрим следующую функцию:

```python linenums="1"
def fn(ls=[1]):
ls.append(2)
return ls

print(fn())
print(fn())
```

```
[1, 2]
[1, 2, 2]
```

Второй вызов функции привел к результату, отличающемуся от первого вызова. Почему так произошло? Значение `ls` по умолчанию мы объявили равным `[1]`. Оба вызова используют значение по умолчанию. Но при втором вызове в данном случае произошло обращение к тому же списку, который был создан в качестве значения по умолчанию при первом вызове. Как это можно проверить?

В Python определена встроенная функция [id](https://docs.python.org/3/library/functions.html#id). Она возвращает целочисленный идентификатор объекта (уникальный и постоянный, пока объект существует). Используем ее, чтобы посмотреть идентификаторы списков.

```python linenums="1"
def fn_with_id(ls=[1]):
print(id(ls))
ls.append(2)
return ls

print(fn_with_id())
print(fn_with_id())
print(fn_with_id([3]))
print(fn_with_id())
```

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Между python и bash везде нужно убрать пустую строку

```
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
```
```bash

123928376604123
[1, 2]
123928376604123
[1, 2, 2]
113928976643254
[3, 2]
123928376604123
[1, 2, 2, 2]
```

Значения идентификаторов у вас могут быть другие. Важно, что в первом, втором и четвертом вызове эти значения одинаковы и отличаются от третьего вызова, у которого значения списка по умолчанию не используется. Такое поведение сохраняется и для пустого списка как значения по умолчанию, и для непустого, как в примере выше.

Одним из решений может быть следующее:

```python linenums="1"
def fixed_fn(ls=None):
if ls is None:
return [2]

ls.append(2)
return ls

print(fixed_fn())
print(fixed_fn())
print(fixed_fn([1]))
print(fixed_fn())
```

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

аналогично убрать пустую строку

```
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
```
```bash

[2]
[2]
[1, 2]
[2]
```

Обратите внимание, что с `set`-ом ситуация другая.

```python linenums="1"
def fn_with_set(_set=set()):
_set.add(2)
print(id(_set))
return _set

print(fn_with_set())
print(fn_with_set())
print(fn_with_set({3}))
print(fn_with_set())
```

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

убрать пустоту

```
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
```
```bash

140214028693696
{2}
140214028693696
{2}
129928985405920
{2, 3}
140214028693696
{2}
```


## Анонимные функции

Функции, определенные при помощи `def`, имеют название, по которому их можно вызвать, но также существуют и анонимные или неименованные функции. Такие функции могут быть определены при помощи оператора `lambda`. Он позволяет задать входные и выходные данные. Самостоятельно можете почитать [документацию](https://docs.python.org/3/reference/expressions.html#grammar-token-lambda-expr).
Expand Down