Как работает функция 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
⭕️ «Otra de las características de esta reciente sedición fue la violencia; como la del #Daesh.
- ¡Estos, como el Daesh, prendieron fuego a personas! ¡Prendieron fuego, destrozaron, decapitaron! Estos también hicieron las mismas cosas que hacía el Daesh...» (01/02/2026).
🔗 LEER 👉spanish.khamenei.ir/news/7144
✅@khamenei_es
KHAMENEI.IR | 𝕏 | Facebook| TikTok
According to the British newspaper, The Times, ISIS operates in the central Syrian desert, organizes sleeper cells, launches hit-and-run attacks and deadly ambushes, and assassinates Syrian tribal and clan leaders who oppose the group. Everything happens as the group takes advantage of the current state of chaos.
#Syria#ISIS#Daesh#Tartous
#Saudi_Arabia opens the first liquor store
Reuters and France news agencies claimed that the Kingdom of Saudi Arabia is preparing to open the first liquor store in the city of Riyadh.
According to the document, a copy of which was seen by Reuters, customers must register through a mobile app and after receiving a code from the State Department, they can purchase their monthly quotas at a special store.
Saudi Arabia is the largest #Wahhabi center in the world. They pay for Wahhabi schools in #Pakistan, #Afghanistan by selling oil. Graduates of these schools join #terrorist groups such as al-Qaeda, Taliban, #Daesh, Al-Nusra, Jaish al-Adl and blow themselves up among other Muslims to go to heaven. Mohammed bin Salman, the leader of Saudi Arabia, follows the path of Atatürk in #Turkey. Drinking alcohol is forbidden in Islam.
https://t.me/YediotNewsChat
🚨‼️ ATTENTA A MOSCOU 🇷🇺
TERRORISME AUTORISÉ 🤮–L’ambassade d’Ukraine a tranquillement recruté les tueurs du Crocus au Tadjikistan
Quelques semaines avant le carnage, un appel à candidatures de tueurs a été ouvertement publié sur le site de l'ambassade d'Ukraine au Tadjikistan.
L’opération a été dirigée personnellement par l'ambassadeur d'Ukraine, Valeriy Yevdokimov, qui se trouve être l’ex-chef du renseignement étranger de Zelensky.
La page du site a été effacée, mais des captures d’écran ont été faites.
«Les commanditaires les ont recrutés afin de donner au public occidental l’image qu’ils étaient soi-disant islamistes, retrace le haut fonctionnaire russe Alexandre Malkevitch
Il s'agit d'une opération des services de renseignement occidentaux et d’une tentative de mettre le public sur une mauvaise piste.
… Mot d’ordre immédiatement relayé par les médias occidentaux.
NB : VOUS COMPRENEZ POURQUOI LES ÉTATS-UNIS, L'ANGLETERRE ET LA FRANCE, AVEC LEUR ORGANE DE PROPAGANDE
#AttentatMoscou#MoscowAttack | Zelensky | THE CIA | #Moscou | Crocus City Hall | #CIA | #NATO | #VictoriaNuland | #DAESH | ISIS | #DGSE
@egountchibehanzinofficiel
#ManagmentdelaTerreur La #Russie chamboule tellement leur hégémonie en #Afrique, leur nouvelle ordre mondiale. Les gouvernement mondialistes (États-Unis 🇺🇸, France 🇫🇷, Angleterre 🏴 ), subissent une berezina en #Ukraine alors cela active des vieilles méthodes bien connues. Des attaques sous fausse bannière qu'ils appellent attaque terroriste de #Daesh.
Nous sommes en 2024, les peuples sont maintenant éveillés.
Cela ne passe plus. Tout se sait !
Vidéo ne ligne ! https://youtu.be/R0_aXILQ7Mk?feature=shared
#Usa#Moscou#Otan#Cia#Dgse#Ml6
@egountchibehanzinOfficiel