Как работает функция 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
Here is the teaser for #Azovstal, my new movie! Are you ready for a powerful journey to one of the most treacherous places on the planet? You will only see it on my channel. View it in 4K at
Youtube.com/c/JohnMarkDougan-BadVolf
Or on Rumble (though not in 4K)
https://rumble.com/user/BadVolf
If you want to see this trailer in 4K, check out he link below:
https://youtu.be/7Ro0R8DpxbU
‘I don’t know what the Azov fighters were taking because they were going under their AGS, their SPG. Heavy shelling. An average person would hardly run towards their bursts because the chance of being hit is high,’ a Vostok battalion fighter, codenamed ‘Forest’, described the actions of Ukrainian nationalists at the Azovstal plant exclusively to RT Documentary.
The plant is enormous, covering 11 square kilometres. It has underground spaces and long tunnels where the Ukrainian military hid from the shelling. This footage shows a fighter from the Vostok battalion explaining the DNR army's tactics in overpowering Azovstal and describing how and from where the fighting was launched. He also points out the remains of ammunition, the destroyed workshop and other premises after the surrender of the Ukrainian military. This episode will be included in our new film, premiering soon.
#Ukraine#Azovstal
Follow: https://t.me/rtdocumentary
На Азовстали продолжают находить свидетельства насилия над людьми.
В ходе обследования территории военные обнаружили недавно использованную доменную печь с останками внутри и одеждой рядом. Найденное отправлено на экспертизу. Надеемся, что худшие ожидания не подтвердятся, хотя, когда речь идёт о сатанинском "Азове", удивляться уже нечему.
Evidence of violence against people continues to be found at the #Azovstal plant.
During the survey of the territory, the military found a recently used blast furnace with remains inside and clothes nearby. The found has been sent for examination. We hope that the worst expectations will not be confirmed, although when they talk about the satanic division "#Azov", there is nothing to be surprised about.
‘I told them [Azov fighters] that they were coming to life, I would have shot them myself... I don’t have an ounce of pity here...’
These are the words of labour veteran Tatyana Ivanovna. She lives in a village near Azovstal. Listen to her story of the Azov battalion shooting the animals in the area and how they almost killed her for trying to save her chickens.
How they mocked her when she asked for water and food: I told their commander: ‘I want to eat, I haven’t eaten for six days …’ And he’s like: ‘I also want to’. But ‘DPR people... came, hugged me, one brought me stew, another brought me bread, and one even thought of bringing sweets’.
We turned to the subjects of the film VolunTears. They helped Tatyana Ivanovna and other residents of the village of Uspenovka by bringing them food, water and medicine.
#Ukraine#Mariupol#Azovstal
Follow: https://t.me/rtdocumentary