Как работает функция 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
🛜🔠🔠🔠🔠🔠
🔠🔠🔠🔠
💛 Alkimyogar
Bu kitobni qancha kop maqtasam arziydi! Qayta qayta tinglang Va o'qing!
Va albatta barcha ORZU maqsadlaringiz Amalga oshganda bizni ham albatta tabassum bilan eslab qo'ying
🤍
🤍 SİZ SO'RAGAN AUDİO KİTOB!
#audiobook
💛@Biglibrary_uz
🔠🔠🔠🔠🔠🔠🔠🔠
🎙 Ichindagi ichindadur
💡 Hayrlı kun kitobsevar qadrdonlarim!! Sizga Juda zo'r
#audiobook🎧 bilan keldim.
Albatta tinglang! Juda ham zo'r kitob! Qancha tariflasam , shuncha so'zlar ojizlik qiladi! Ming marta maqtagandan ko'ra bir marta o'zingiz mazasini tatib koring 🫂
Bu kitobni o'qiganlar Yoki tinglaganlar bormi ,
🔥 reaksiyalarni bosib qoying
@Milliarderlarim
#Narratorr#Audiobook#amp#TTS
Join the Narratorr - Audiobook & TTS beta on ✈️#TestFlight
🔗 Link: https://testflight.apple.com/join/Fv19nvDd
Shared by Dimitri
📖Title : The Frozen River
✍️Author : Ariel Lawhon
⭐️Rating : 4.38/5 (Goodreads)
📆Published : Dec 05, 2023
————————————————
Summary:The Frozen River by Ariel Lawhon is a historical mystery set in 1789 Maine. Midwife and healer Martha Ballard is called to examine the body of a man found trapped in the frozen Kennebec River. While authorities quickly declare the death an accident, Martha suspects something far darker. As she records events in her diary and follows the clues, she uncovers a web of violence, secrets, and injustice involving powerful members of the community. Determined to seek the truth despite threats and social pressures, Martha risks her reputation and safety while fighting for justice in a society where women’s voices are often ignored.
————————————————
#fiction#mystery#audiobook#historical#thriller#ariellawhon#thefrozenriver@Bookslibraryofficial
📖Title : More Days at the Morisaki Bookshop
✍️Author : Satoshi Yagisawa
⭐️Rating : 3.85/5 (Goodreads)
📆Published : Dec 06, 2011
————————————————
Summary:More Days at the Morisaki Bookshop follows Takako as she continues healing while living above her uncle’s secondhand bookshop in Tokyo’s Jimbocho district. Surrounded by books and familiar faces, she confronts lingering grief, evolving relationships, and quiet uncertainties about the future. The novel focuses on small, meaningful moments, showing how literature, routine, and human connection gently restore a sense of belonging. Through everyday interactions, it portrays healing as gradual, imperfect, and deeply tied to community, memory, and the comforting presence of books.
————————————————
#fiction#japan#cozy#audiobook#romance#moredaysatthemorisakibookshop#satoshiyagisawa@Bookslibraryofficial@free_novellas@eternalmantra
📖Title : Bemused
✍️Author : Farrah Rochon
⭐️Rating : 3.92/5 (Goodreads)
📆Published : Jan 07, 2025
————————————————
Summary:Five sheltered sisters living in a quiet seaside village learn that they are the legendary Muses, daughters of Mnemosyne, Goddess of Memory. After their mother is kidnapped by Hades, the sisters are forced to leave their protected lives behind. Guided by Calliope’s leadership, they journey through dangerous lands, face mythical trials, and uncover their divine powers. Along the way, they confront fear, doubt, and destiny itself. Through music, storytelling, courage, and unity, the sisters strengthen their bond and transform from overlooked performers into heroic figures, embracing their true identities and shaping their own legendary “gospel truth.”
————————————————
#fantasy#mythology#retellings#fiction#historicalfiction#audiobook#bemused#farrahrochen@Bookslibraryofficial@free_novellas@eternalmantra