Telegram Group & Telegram Channel
🐍 Задача с подвохом: mutable default arguments в Python

🔹 Уровень: Advanced
🔹 Темы: изменяемые аргументы по умолчанию, функции, ловушки с list и dict

📌 Условие

Что выведет следующий код?


def append_to_list(value, my_list=[]):
my_list.append(value)
return my_list

print(append_to_list(1))
print(append_to_list(2))
print(append_to_list(3))


Вопросы

1. Почему результат выглядит неожиданно?
2. Как исправить это поведение?
3. Когда стоит использовать изменяемые аргументы по умолчанию — если вообще стоит?

🔍 Разбор

Ожидаемый вывод:

[1]
[1, 2]
[1, 2, 3]


🔧 Почему так происходит

- Аргументы по умолчанию вычисляются один раз — во время определения функции, а не при каждом вызове.
- Значение my_list=[] создаётся один раз и затем используется повторно при всех вызовах.
- Все вызовы append_to_list изменяют один и тот же список.

⚠️ Подвох

Это один из самых коварных багов в Python, особенно среди начинающих — кажется, что my_list должен быть новым на каждый вызов, но это не так.

🧠 Вывод

- Никогда не используй изменяемые типы (list, dict, set) как значения по умолчанию.
- Вместо этого используй None и создавай новый объект вручную:


def append_to_list(value, my_list=None):
if my_list is None:
my_list = []
my_list.append(value)
return my_list


Тогда вывод будет:

[1]
[2]
[3]


📌 Это правило относится ко всем изменяемым типам: [], {}, set() и кастомные классы.



group-telegram.com/pythonl/4824
Create:
Last Update:

🐍 Задача с подвохом: mutable default arguments в Python

🔹 Уровень: Advanced
🔹 Темы: изменяемые аргументы по умолчанию, функции, ловушки с list и dict

📌 Условие

Что выведет следующий код?


def append_to_list(value, my_list=[]):
my_list.append(value)
return my_list

print(append_to_list(1))
print(append_to_list(2))
print(append_to_list(3))


Вопросы

1. Почему результат выглядит неожиданно?
2. Как исправить это поведение?
3. Когда стоит использовать изменяемые аргументы по умолчанию — если вообще стоит?

🔍 Разбор

Ожидаемый вывод:

[1]
[1, 2]
[1, 2, 3]


🔧 Почему так происходит

- Аргументы по умолчанию вычисляются один раз — во время определения функции, а не при каждом вызове.
- Значение my_list=[] создаётся один раз и затем используется повторно при всех вызовах.
- Все вызовы append_to_list изменяют один и тот же список.

⚠️ Подвох

Это один из самых коварных багов в Python, особенно среди начинающих — кажется, что my_list должен быть новым на каждый вызов, но это не так.

🧠 Вывод

- Никогда не используй изменяемые типы (list, dict, set) как значения по умолчанию.
- Вместо этого используй None и создавай новый объект вручную:


def append_to_list(value, my_list=None):
if my_list is None:
my_list = []
my_list.append(value)
return my_list


Тогда вывод будет:

[1]
[2]
[3]


📌 Это правило относится ко всем изменяемым типам: [], {}, set() и кастомные классы.

BY Python/ django


Warning: Undefined variable $i in /var/www/group-telegram/post.php on line 260

Share with your friend now:
group-telegram.com/pythonl/4824

View MORE
Open in Telegram


Telegram | DID YOU KNOW?

Date: |

Investors took profits on Friday while they could ahead of the weekend, explained Tom Essaye, founder of Sevens Report Research. Saturday and Sunday could easily bring unfortunate news on the war front—and traders would rather be able to sell any recent winnings at Friday’s earlier prices than wait for a potentially lower price at Monday’s open. "The inflation fire was already hot and now with war-driven inflation added to the mix, it will grow even hotter, setting off a scramble by the world’s central banks to pull back their stimulus earlier than expected," Chris Rupkey, chief economist at FWDBONDS, wrote in an email. "A spike in inflation rates has preceded economic recessions historically and this time prices have soared to levels that once again pose a threat to growth." On February 27th, Durov posted that Channels were becoming a source of unverified information and that the company lacks the ability to check on their veracity. He urged users to be mistrustful of the things shared on Channels, and initially threatened to block the feature in the countries involved for the length of the war, saying that he didn’t want Telegram to be used to aggravate conflict or incite ethnic hatred. He did, however, walk back this plan when it became clear that they had also become a vital communications tool for Ukrainian officials and citizens to help coordinate their resistance and evacuations. 'Wild West' These entities are reportedly operating nine Telegram channels with more than five million subscribers to whom they were making recommendations on selected listed scrips. Such recommendations induced the investors to deal in the said scrips, thereby creating artificial volume and price rise.
from jp


Telegram Python/ django
FROM American