Как работает функция 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
Any form of meningitis is a medical emergency.
Download our latest #CerebrospinalMeningitis situation report for a summary of the disease situation and our response activities
🔗
https://ncdc.gov.ng/diseases/sitreps/?cat=6&name=An%20Update%20of%20Meningitis%20Outbreak%20in%20Nigeria
We have published our latest situation report on #CerebrospinalMeningitis.
This report provides a summary of the current epidemiological situation in Nigeria, and our preparedness and response activities.
🔗https://ncdc.gov.ng/diseases/sitreps/?cat=6&name=An%20Update%20of%20Meningitis%20Outbreak%20in%20Nigeria
#TakeResponsibility
The highest burden of #CerebrospinalMeningitis in Nigeria occurs in the “Meningitis Belt” which includes all 19 states in the Northern region, the FCT, and some southern states.
Ensure you and your loved ones have received the appropriate vaccination required to protect against #meningitis
Public Health Advisory: https://ncdc.gov.ng/news/508/cerebrospinal-meningitis-public-health-advisory
Vaccination is the best prevention measure against #CerebrospinalMeningitis.
Ensure you complete the routine immunisation for your children or wards to keep them safe and #healthy.
#TakeResponsibility
#CerebrospinalMeningitis (CSM) is an easily transmissible disease with confirmed cases reported all year round in Nigeria.
Download our latest #CSM situation report for a summary of the disease situation and our response activities
🔗https://ncdc.gov.ng/diseases/sitreps/?cat=6&name=An%20Update%20of%20Meningitis%20Outbreak%20in%20Nigeria
#TakeResponsibility
Vaccination is the best prevention measure against #CerebrospinalMeningitis.
Ensure you complete Nigeria's routine immunisation schedule for your children or wards to keep them safe and #healthy.
#DefeatMeningitis
Are you familiar with the signs of #Meningitis in ADULTS?
Know the signs and symptoms to report early to a healthcare facility when noticed.
#CerebrospinalMeningitis is a MEDICAL EMERGENCY!
#StaySafeStayHealthy#WorldMeningitisDay
🔗
https://youtu.be/ZhZdin-Cn9s?feature=shared
Vaccination is the best prevention measure against #CerebrospinalMeningitis.
Ensure you complete Nigeria's routine immunisation schedule for your children or wards to keep them #safe from vaccine-preventable diseases.
#DefeatMeningitis
#WorldMeningitisDay