Как работает функция 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
#Explosion reported in #Mekelle; Officials say no casualties
An explosion occurred late Thursday in Mekelle near the Social Science campus of Mekelle University, though officials say there were no casualties or property damage.
Redahegn Feseha, head of the Mekelle Peace and Security Bureau, told local radio that the blast happened at around 9:30 p.m. near the upper gate of the city’s business campus. He described the incident as a deliberate act aimed at creating fear rather than causing harm, urging residents to remain calm and to condemn what he called an “act of terror.”
Residents reported a mix of fear and confusion. “I was sitting with my family when we heard a loud bang. My kid and my wife were terrified,” said one resident. Another added, “At first, we thought it was a drone attack or something falling. But later we heard it was a bomb.”
https://www.facebook.com/share/p/19x2dWByCq/
🇨🇳Le bilan de l’explosion dans une usine de feux d’artifice en Chine s’est alourdi à 21 morts et 61 blessés, a rapporté la Télévision centrale de Chine.
#chine#explosion
🇨🇳 Une explosion s’est produite dans une usine de feux d’artifice en Chine, faisant 3 morts et 25 blessés, a rapporté l’agence Xinhua.
Vidéo: My Fair Lady/X
#chine#usine#explosion
🇮🇷🇮🇱🇺🇸 Plusieurs civils ont été tués dans l’explosion de mines dissimulées dans des boîtes de conserve, larguées par des avions américains et israéliens près de la ville de Chiraz, dans le sud de l’Iran, rapporte l’agence Tasnim.
#iran#explosion#bilan
🇺🇸Cinq personnes ont été blessées à la suite d’une explosion de gaz dans une église de Boonville (État de New York), a rapporté la chaîne CBS News.
#étatsunis#église#explosion
🇨🇳 Une explosion s’est produite dans une usine de feux d’artifice en Chine, faisant 3 morts et 25 blessés, a rapporté l’agence Xinhua.
Vidéo: My Fair Lady/X
#chine#usine#explosion
🇬🇧 En Irlande du Nord, un homme a été arrêté après l'explosion d'une voiture devant un commissariat de police. Des perquisitions sont en cours à plusieurs adresses de Belfast, indique un communiqué de la police régionale.
#royaumeuni#voiture#explosion
🇦🇪Une explosion a eu lieu dans un immeuble du centre financier international de Dubaï, aux Émirats arabes unis, a rapporté le commentateur politique Mario Nawfal sur le réseau social X.
#émirats#explosion#immeuble
🇬🇧 Un obus non explosé de la Seconde Guerre mondiale a été neutralisé par une explosion contrôlée dans la ville de Plymouth, dans le sud-ouest de l'Angleterre. La BBC a diffusé une vidéo de l'explosion.
La bombe aérienne allemande SC250, une bombe à explosion pesant environ un quart de tonne, a été découverte le 30 avril par un propriétaire qui creusait une tranchée sur son terrain dans le quartier de Southway. La zone a été bouclée et les habitants de près de 1.200 maisons avoisinantes ont dû évacuer leurs domiciles.
#royaumeuni#explosion#obus
🇧🇮 Des dizaines de personnes ont péri dans l’incendie provoqué par des explosions survenues dans un dépôt de munitions à Bujumbura, la capitale économique du Burundi, a rapporté l’Agence France-Presse (AFP).
#burundi#explosion#incendie#victimes