Как работает функция reload()?
Эта функция нужна для того, чтобы перезагрузить изменившийся код из py-файла без рестарта интерпретатора.
Дело в том, что любой импортированный модуль при повторном импорте не будет перечитывать файл. Функция импорта вернёт уже загруженный в память объект модуля. Чтобы обновить код, нужно либо перезапустить всю программу, либо использовать функцию reload()
from importlib import reload
reload(my_module)
🔸 Функция reload() принимает в качестве аргумента только объект модуля или пакета. Она не может перезагрузить класс или функцию. Только весь файл целиком!
🔸 Перезагрузка пакета перезагрузит только его файл __init__.py, если он есть. Но не вложенные модули.
🔸Она не может перезагрузить ранее не импортированный модуль.
🔸При вызове функция reload() перечитывает и перекомпилирует код в файле, создавая новые объекты. После создания новых объектов перезаписывается ранее созданный неймспейс этого модуля.
Это значит, что если где-то этот модуль импортирован через import и обращение к атрибутам происходит через неймспейс (имя) модуля, то такие атрибуты обновятся.
Если какие-либо объекты из этого модуля импортированы через from то они будут ссылаться на старые объекты.
Напишем простой модуль
# mymodule.py
x = 1
Теперь импортируем модуль и отдельно переменную х из модуля
>>> import mymodule
>>> from mymodule import x
>>> print(mymodule.x)
1
>>> print(x)
1
Не перезапуская интерпретатор вносим изменения в модуль
# mymodule.py
x = 2
Делаем перезагрузку модуля и проверяем х ещё раз
>>> reload(mymodule)
>>> print(mymodule.x)
2
>>> print(x)
1
То же самое будет если присвоить любой объект переменной (даже словарь или список)
Повторный импорт обновляет значение
>>> from mymodule import x
>>> print(x)
2
🔸Созданные инстансы классов не обновятся после перезагрузки модуля. Их придётся пересоздать.
#tricks#basic
🚀 U.S. President Trump Considers Maritime Blockade Against Iran
On April 12, U.S. President Donald Trump posted on Truth Social about a potential maritime blockade against Iran. According to BlockBeats, Trump suggested this measure if Iran does not make concessions. The statement highlights ongoing tensions between the United States and Iran, with the possibility of escalating actions if diplomatic solutions are not reached.
#Trump#Iran#MaritimeBlockade#USIranTensions#Diplomacy#TruthSocial#TrumpStatement#IranConcessions
🚀 Trump Criticizes Iran's Media Tactics on Truth Social
U.S. President Donald Trump expressed his views on Iran's media strategies on April 11 via Truth Social. According to BlockBeats, Trump stated that Iranians are more adept at handling fake news media and public relations than engaging in warfare. He remarked that Iran seems unaware of its lack of leverage, aside from short-term 'extortion' through international waterways. Trump concluded that Iran's current existence is solely for negotiation purposes.
#Trump#Iran#MediaTactics#FakeNews#PublicRelations#Negotiation#TruthSocial#Extortion#InternationalWaterways
США повышают пошлины на южнокорейские товары 📊
Президент США Дональд Трамп заявил в понедельник, что повышает пошлины на южнокорейские автомобили, пиломатериалы, фармацевтические препараты и другие товары с 15% до 25%. 💸
Основные моменты 📌
Причина: Трамп сослался на то, что Южная Корея не ратифицировала торговое соглашение, которое, по его словам, было заключено с президентом Ли Чжэ Мёном в прошлом году.
Заявление: «Поскольку корейский законодательный орган не ратифицировал наше историческое торговое соглашение, что является его прерогативой, я повышаю южнокорейские ТАРИФЫ на автомобили, пиломатериалы, фармацевтическую продукцию и все другие взаимные ТАРИФЫ с 15% до 25%», — написал Трамп в своём посте в социальной сети Truth Social.
Предыстория: Ранее в этом месяце сообщалось, что Южная Корея будет добиваться льготных условий для снижения тарифов США на импорт микросхем памяти.
🤑Следите за нашими обновлениями, чтобы оставаться в курсе последних изменений в экономике и политике!
#США#ЮжнаяКорея#Пошлины#Трамп#ТорговоеСоглашение#Автомобили#Пиломатериалы#ФармацевтическиеПрепараты#Тарифы#TruthSocial#ЛиЧжэМён#МикросхемыПамяти#Импорт
🚀 Polymarket Predicts Low Probability of Trump Ending Iran Military Action by April 21
The probability of U.S. President Donald Trump announcing the end of military action against Iran by April 21 has significantly decreased to 21%, according to Odaily. This marks a 22% drop in the past 24 hours, with the total trading volume for this event contract nearing $17 million.
The contract stipulates that if President Trump, the U.S. government, or the military officially announces the end of the military action initiated on February 28, 2026, by the specified date (Eastern Time), the market will resolve as 'yes.' Otherwise, it will resolve as 'no.' Valid statements must clearly indicate the end of the action. Informal statements, anonymous sources, or leaked information do not qualify. However, Trump's public written statements, such as posts on his "Truth Social" account, and videos on his social media accounts are considered valid. The primary basis for market resolution is official statements from the U.S. government and/or its representatives, with additional consideration given to consensus from other credible reports.
On the first day of a temporary ceasefire between the U.S. and Iran, Israeli forces launched the largest airstrike against Hezbollah since the conflict began. Iran claimed this violated the ceasefire agreement, leading to the closure of the Strait of Hormuz and threats of deterrent action against Israeli military targets. The White House announced that the first round of U.S.-Iran talks will take place on the 11th in Pakistan. However, Iran stated that three key ceasefire terms have been violated, undermining the "basis for negotiations." Despite this, Iran's Deputy Foreign Minister, Saeed Khatibzadeh, confirmed that the Iranian delegation will attend the talks in Islamabad, Pakistan.
#Polymarket#Trump#Iran#militaryaction#US#ceasefire#Israel#Hezbollah#StraitOfHormuz#WhiteHouse#USIranTalks#Pakistan#SaeedKhatibzadeh#TruthSocial#USGovernment