Как работает функция 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
🌎 In ancient China, giant panda pelts were considered symbols of peace and friendship. Emperors gifted them to rival kingdoms as precious gestures, showing diplomacy in action through nature’s rarest bear. ✨
#history⚡#animals⚡#diplomacy
👉subscribe Interesting Planet
🚨🇺🇸TRUMP TELLS IRAN "CALL US" AS PUTIN HOSTS TEHRAN'S TOP DIPLOMAT
🔹 Iranian Foreign Minister Abbas Araghchi lands in St. Petersburg today for emergency talks with Putin 🇷🇺
🔹 Trump abruptly canceled US-Iran face-to-face meeting scheduled in Pakistan, blaming Tehran's "excessive demands" 📞❌
🔹 Nine-week conflict continues with mutual blockades choking energy markets — oil prices surge nationwide 💰⛽
🔹 Strait of Hormuz remains partially closed as Iran seeks Russian backing after US diplomacy collapsed 🚢🔒
"The ball is in their court — call us when you're ready to be serious," Trump signals 📱
This is getting messy fast 😬🔥
#USNews#Iran#diplomacy
@america
Faces of #Uzbekistan#Diplomacy
Ambassadors, permanent representatives and general consuls of Uzbekistan abroad with the First Deputy Chair of the Senate of the Parliament Sodyq Safaev and the Deputy Minister of Foreign Affairs Sherzod Asadov, after the seminar training organised by the Senate.
P.S. Could you find only two women?
@Diplomatika
🚨🇺🇸U.S. INTEL: IRAN REJECTS PEACE TALKS
🔹 Multiple intelligence agencies assess Tehran unwilling to negotiate seriously 🕵️♂️
🔹 Iran believes it's winning, doesn't trust Trump after previous attacks mid-negotiations 💪
🔹 Trump claims military will wrap up Iran campaign within 2-3 weeks ⏰
🔹 President threatens to bomb ALL Iranian power plants if no deal - potential war crime ⚡
🔹 Tehran foreign ministry denies asking for ceasefire despite Trump's progress claims 🗣️
Iran wants real peace talks, not temporary fixes according to Pakistani officials! This war is FAR from over 😤🔥
#USNews#Iran#Trump#diplomacy
@america
🌍 The Arctic Council brings together eight countries to manage Arctic resources and navigate disputes, making this region one of the world’s best examples of peaceful geopolitical cooperation. ✨
#geopolitics⚡#Arctic⚡#diplomacy⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
The Venezuelan government accepted Washington’s offer to restart dialogue only weeks ahead of presidential elections on July 28. President Maduro emphasizes any talks will have Venezuela's sovereignty as a starting point.
Full story: https://venezuelanalysis.com/news/venezuela-to-restart-direct-talks-with-us-maduro-announces/
#Venezuela#UnitedStates#Diplomacy
🚨🇨🇺🇺🇸CUBA CONFIRMS SECRET TALKS WITH TRUMP ADMINISTRATION
🔹 Cuban President Díaz-Canel publicly admits holding bilateral talks with US officials 🤝
🔹 Discussions aim for historic economic deal - biggest opening since 1961 revolution 💰
🔹 Cuba releases 51 prisoners as Vatican-brokered goodwill gesture ahead of negotiations 🕊️
🔹 Trump threatens "friendly takeover" if Cuba refuses to make deal with Washington 💪
🔹 Island faces fuel crisis with NO oil shipments for 3 months due to US blockade ⛽
🔹 Secretary Rubio reportedly in secret talks with Raul Castro's grandson Raulito 🤐
This could END 65 years of Cold War hostility - but at what price? 🔥🌎
#Cuba#diplomacy#Trump
@america
📰 NEWS | Venezuela Reclaims US Diplomatic Venues as Rodríguez Promotes ‘Faith Diplomacy’
Venezuela has officially retaken its diplomatic headquarters in Washington, DC, after the properties were under US State Department control since 2023. Officials re-hoisted the national flag and announced a rehabilitation process to restore full consular services for Venezuelan nationals.
The development follows renewed diplomatic ties between Caracas and Washington and a US sanctions waiver permitting operations of Venezuelan missions. Authorities say the facilities will address passport processing, legal documentation, and citizen assistance after years of restricted access.
Read the full report here 👉🏾https://venezuelanalysis.com/news/venezuela-reclaims-us-diplomatic-venues-as-rodriguez-promotes-faith-diplomacy/
#diplomacy#Religion#USVenezuelaRelations
politics
Somaliland and the Evolution of Diplomatic Engagement After 34 Years of Isolation. Read.
https://borkena.com/2026/01/01/somaliland-and-the-evolution-of-diplomatic-engagement-after-34-years-of-isolation/#SomalilandRecognition#Somaliland#Diplomacy