Как работает функция 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
Green University Organized “Youth Day” Events
On April 16, in celebration of Youth Day, Green University organized a series of events covering various areas for students and young people.
🖥The program included psychological consultations, English language classes, sports competitions, and the “Zakovat” intellectual game. In addition, a preventive awareness session with representatives of the internal affairs bodies was held, followed by an open Q&A session on legal topics.
#GreenUniversity#YouthDay#StudentLeague
👉ReadMore ___________________
Green University’da “Yoshlar kuni” tadbirlari o‘tkazildi
16-aprel “Yoshlar kuni” munosabati bilan Green University’da talabalar va yoshlar uchun turli yo‘nalishlarni qamrab olgan tadbirlar tashkil etildi.
🖥Dastur doirasida psixologik konsultatsiyalar, ingliz tili mashg‘ulotlari, sport musobaqalari hamda “Zakovat” intellektual o‘yini o‘tkazildi. Shuningdek, ichki ishlar organlari vakillari ishtirokida profilaktik uchrashuv va huquqiy mavzudagi ochiq savol-javob sessiyasi tashkil etildi.
#GreenUniversity#YoshlarKuni
👉Batafsil
✉️[email protected]
☎️ +998 55 512 00 77
📍Location
🌐Website | 📱Telegram | 📱Instagram | 📱LinkedIn | 🟥YouTube
Highlights from the Youth Day at Green University.
#GreenUniversity#YouthDay#StudentLeague#TeamSpirit#Leadership
__________________________
Green University Yoshkar kunidan lavhalar.
#GreenUniversity#YoshlarKuni#TalabalarLigasi#TalabalarHayoti#Jamoaviylik#Liderlik
✉️[email protected]
☎️ +998 55 512 00 77
📍Location
🌐Website | 📱Telegram | 📱Instagram | 📱LinkedIn | 🟥YouTube
📌On April 9, Green University actively celebrated Youth Day with a dynamic and engaging program that brought together students, faculty, and administration.
🗣️Throughout the day, participants took part in a wide range of activities — from educational workshops and intellectual games to open lectures and cultural events. The atmosphere was vibrant, reflecting the energy, enthusiasm, and ambition of the youth.
A special highlight was the opening of the Student League sports competitions, where the university rector, Dr. Bakhtiyor Pulatov personally took part alongside students. His participation made the event even more inspiring, strengthening the spirit of unity, teamwork, and friendly competition.
✅Youth Day at Green University once again proved that the university is not only a center of education, but also a space where students actively develop, engage, and succeed together.
#GreenUniversity#YouthDay#StudentLeague#StudentLife#TeamSpirit#Leadership
👉ReadMore __________________________
📌9-aprel kuni Green University'da Yoshlar kuni keng qamrovli va mazmunli dastur asosida faol tarzda nishonlandi. Tadbirlar davomida talabalar, professor-o‘qituvchilar hamda universitet rahbariyati birlashdi.
🗣️Kun davomida ishtirokchilar turli ta’limiy seminarlar, intellektual o‘yinlar, ochiq ma’ruzalar va madaniy tadbirlarda faol qatnashdilar. Muhit yoshlarga xos energiya, ishtiyoq va intilishlarga boy bo‘ldi.
Tadbirning eng esda qolarli biri Talabalar ligasi sport musobaqalarining ochilish marosimi bo‘ldi. Unda universitet rektori, professor Baxtiyor Pulatov ham talabalar bilan bir qatorda ishtirok etib, o‘zining faol ishtiroki orqali birlik, jamoaviylik va sog‘lom raqobat muhitini yanada mustahkamladi.
✔️Green University'da Yoshlar kuni yana bir bor universitet nafaqat ta’lim maskani, balki talabalar har tomonlama rivojlanadigan, faol ishtirok etadigan va birgalikda yuksaladigan muhit ekanini namoyon etdi.
#GreenUniversity#YoshlarKuni#TalabalarLigasi#TalabalarHayoti#Jamoaviylik#Liderlik
👉Batafsil
✉️[email protected]
☎️ +998 55 512 00 77
📍Location
🌐Website | 📱Telegram | 📱Instagram | 📱LinkedIn | 🟥YouTube