Как работает функция 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
#Italia
❗️BREAKING ANSA - Blitz della Presidente del Consiglio Giorgia #Meloni (#FdI|ECR) nel Golfo. La ‘premier’ è appena atterrata a Gedda e nei prossimi giorni incontrerà i principali leader della zona e visiterà #ArabiaSaudita, #Emirati e #Qatar.
Fonti di Palazzo Chigi sottolineano che la missione a sorpresa della premier mira, tra l'altro, al rafforzamento della sicurezza energetica nazionale.
Si tratta della prima visita nella regione da parte di un leader di Ue, G20 e Nato dall'inizio del conflitto. Il Golfo rappresenta infatti una fonte cruciale di petrolio e gas per l'Italia e ha un ruolo determinante nell'andamento dei prezzi energetici globali.
La missione punta anche a rafforzare le relazioni" con queste nazioni del Golfo e "ribadire il sostegno dell'Italia di fronte agli attacchi iraniani, consolidando al contempo un partenariato strategico sempre più solido.
@OsservatorioItaliano
News: #Somaliland leader departs for #UAE, seeks deeper ties as regional stakes rise
Somalia's northwestern breakaway region of Somaliland President Abdirahman Mohamed Abdullahi departed for the United Arab Emirates on Tuesday, leading a high-level delegation that includes cabinet ministers and senior advisers, his office said.
The trip follows a formal invitation from the UAE government, with President Abdirahman Mohamed expected to attend a conference focused on development and intergovernmental cooperation.
Officials said he is also scheduled to hold meetings in #Abu_Dhabi with senior #Emirati leaders to discuss strengthening bilateral relations.
Talks are expected to center on development projects and investment, areas where the UAE has played a significant role in Somaliland's economy. Emirati logistics firm #DP_World has invested about $442 million in the expansion and .....
https://web.facebook.com/AddisstandardEng/posts/pfbid02vruBZ8aULb9h5RjA2RsY29mzkbAHJ12PxaQznHBY1Zrsq9GGTQzzwa8qRMyK9tUal
What #Sudan can teach #Ethiopia as #Eritrea conflict looms
As African leaders gathered at the annual #African_Union summit in #Addis_Abeba last week under the seemingly non-urgent theme of “water sustainability,” there was only passing acknowledgement that “silencing the guns on our continent remains a challenge.”
Yet the cadence of conflict — and the threat of new war — hung low over the horizon. It never felt proximate enough, however, to darken the mood of the festivities.
Ethiopian Prime Minister Abiy Ahmed was keen to show off his clean and modern metropolis, financed and looking like a “mini-me” version of his #Emirati backers in #Dubai. As host of the three-day summit, Abiy’s heads of state guests showed deference by making no mention of his increasingly bellicose calls for sea access — and the indirect threat to Eritrea, its neighbor.
Nor was there talk of Asmara’s response…..
https://web.facebook.com/AddisstandardEng/posts/pfbid0obN5Kafo8UNTY59yKCGZdnA3LrbsDe5ztUgt28cTAUnTpDGbj4njfoj8yHH63sgnl
In un evento online organizzato da The New York Times parla #Netanyahu: "Non abbiamo finito con #Tehran" e #TomBarrack, Ambasciatore #USA in #Turchia parla negli #Emirati: "Abbiamo ancora da vedere in merito a ciò che potrebbe fare #Israele in #Iran".
I recenti attacchi alle raffinerie saudite hanno evidenziato una notevole vulnerabilità delle strutture saudite e posto interrogativi anche sull affidabilità dei sistemi antimissile Patriot – di produzione statunitense – a cui ne è stata affidata la difesa. In questo senso, l’attacco alle raffinerie saudite rappresenta un duro colpo alla credibilità degli Stati Uniti, segnando inoltre un punto di svolta nella guerra dello #Yemen: un conflitto in cui ormai da anni si fronteggiano le forze governative – sostenute da #Arabia Saudita, #Emirati Arabi e #StatiUniti – e i ribelli #Houti sostenuti dall’#Iran. Un conflitto rispetto al quale l’Arabia Saudita non ha, per il momento, ammorbidito la propria linea oltranzista, nonostante le oltre 70.000 vittime già prodotte dal conflitto, la più grave crisi umanitaria attualmente esistente sul pianeta – secondo l’ ONU –, ed un atteggiamento ormai quasi disfattista da parte degli Emirati Arabi. Il mio articolo per l'Atlante geopolitico di Treccani
http://www.treccani.it/magazine/atlante/geopolitica/Il_Vicino_Oriente_dopo_gli_attacchi_alle_raffinerie_saudite.html