Как работает функция 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
🪐 The galaxy cluster CLASH J0152.7-1357, observed by both Hubble and ground-based telescopes, contains vast amounts of dark matter—an invisible substance revealed only by its powerful gravitational pull on galaxies and hot gas. Despite being undetectable by any normal telescope, dark matter outweighs the visible content in CLASH J0152.7-1357, shaping the cluster and allowing scientists to map where this mysterious material gathers in the cosmos. ✨
#darkmatter⚡#galaxycluster⚡#cosmos⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The galaxy cluster MACS J0416.1-2403 is held together by enormous amounts of dark matter—an invisible substance that does not emit or reflect light, but adds enough gravity to bind thousands of galaxies and clouds of hot gas. Observations show that the visible matter in MACS J0416.1-2403 makes up only a small fraction of the total mass, highlighting how most of the cluster’s true weight comes from this mysterious, unseen ingredient shaping the universe on the largest scales. ✨
#darkmatter⚡#galaxycluster⚡#mysteries⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The galaxy cluster CL0024+17, located about 5 billion light-years away, has helped scientists visualize dark matter using a phenomenon called gravitational lensing—where the cluster's gravity bends the light from even more distant galaxies and creates giant arcs in the sky. This invisible "scaffolding" of dark matter shapes the cluster's structure and reveals mysterious regions that emit no light but hold enormous mass, showing the universe is built on something we still cannot see. ✨
#darkmatter⚡#galaxycluster⚡#mysteries⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 In the galaxy cluster El Gordo, astronomers have observed evidence that most of its mass is not from visible matter but from dark matter—a mysterious, invisible substance that outweighs all the galaxies and gas combined. Detailed gravitational lensing (where gravity bends and magnifies the light from more distant galaxies) reveals vast, hidden regions in El Gordo, confirming that dark matter acts as a cosmic glue, binding this colossal cluster together and shaping its structure on a grand scale. ✨
#darkmatter⚡#lensing⚡#galaxycluster⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Scientists studying the distant galaxy cluster MACS J1149+2223 use it as a window into the fate of the cosmos, tracking how the accelerated expansion driven by dark energy might eventually push galaxies so far apart that their light can never reach each other again. Over unimaginable timescales, clusters like MACS J1149+2223 will fade from view as the universe expands, leaving behind only a cold, dark emptiness—an ending known as "cosmic isolation" that awaits even the brightest galaxies. ✨
#universe⚡#expansion⚡#darkenergy⚡#galaxycluster⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Within the distant galaxy cluster MACS J1423.8+2404, astronomers have measured the effects of dark energy—a mysterious force causing the universe to expand faster and faster over time. By studying how galaxies in this cluster are drifting apart, scientists collect real-world evidence that dark energy acts like a kind of "anti-gravity," pushing the vast cosmic web ever outward and shaping the fate of everything we see in the universe. ✨
#darkenergy⚡#galaxycluster⚡#expansion⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 In the galaxy cluster Abell 3827, astronomers have observed four galaxies merging and spotted what may be the first hints that dark matter—an invisible substance shaping the cosmos—can interact with itself beyond just gravity. By watching how dark matter halos (the unseen envelopes around galaxies) seem to lag behind their stars during the collision, scientists are piecing together clues about this mysterious material that outweighs all ordinary matter in the universe. ✨
#darkmatter⚡#abell3827⚡#galaxycluster⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries