Как работает функция 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
News: Following months of mutual accusations, #Eritrean President Isaias Afwerki accuses #Ethiopia of declaring war, dismisses Red Sea narrative
Eritrean President #Isaias Afwerki on Monday accused Ethiopia of declaring war on Eritrea and rejected narratives framing the tensions as a dispute over #Red_Sea access, in comments aired on Eritrean state television.
Following an extended discussion on United States foreign policy, President Isaias turned to his deteriorating relations with Ethiopia’s ruling party.
He rejected claims that tensions between the two countries are linked to access to the Red Sea, insisting that Eritrea harbors no such ambition. “For us, it is not directly about the Red Sea,” he said.
The Eritrean leader accused Ethiopia’s ruling Prosperity Party of advancing a broader militarized agenda, claiming that armed conflicts have persisted across the country despite the signing of the Pretoria peace agreement.
Isaias further alleged that ...
Read more: https://addisstandard.com/?p=54519
News: #Saudi deputy foreign minister meets #Ethiopian FM week after Isaias talks in Asmara
Saudi Arabia’s Vice Minister of Foreign Affairs, Waleed A. M. Elkhereiji, met with Ethiopia’s Minister of Foreign Affairs, Gedion Timothewos, in Addis Abeba, a week after holding talks with #Eritrean President #Isaias Afwerki in #Asmara.
According to a statement from the Ethiopian Ministry of Foreign Affairs, the two officials discussed the “strong and longstanding bilateral relations” between Ethiopia and the Kingdom of Saudi Arabia, underscoring the importance of elevating ties to “a new high.” They also exchanged views on regional peace & security issues of mutual interest.
Ethiopia’s Minister of Foreign Affairs offered no additional information in the statement.
The meeting comes a week after Saudi Vice Foreign Minister Waleed A. M. Elkhereiji held talks in Asmara with Eritrean President...
Read more: https://addisstandard.com/saudi-deputy-foreign-minister-meets-ethiopian-fm-week-after-isaias-talks-in-asmara/
🚀✨ ¡Comenzamos una nueva etapa en nuestra serie de las Sagradas Escrituras!
Hoy nos adentramos en los Libros Proféticos con uno de sus gigantes: Isaías.
Junto a Daniel Osorio, descubriremos su mensaje lleno de esperanza y promesa mesiánica.
📅 Hoy | 🕑 2:00 p.m.
📻 Tu Emisora Minuto de Dios
🎙#LaCatequesis
📖 “El pueblo que caminaba en tinieblas vio una gran luz” (Is 9,1).
#fesencillavidailuminada#minutodediosmed#trilocosxjesus#Biblia#Isaias#Profeticos#PalabraQueTransforma