Как работает функция 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 lithosphere, atmosphere, hydrosphere, and biosphere constantly exchange matter—volcanic eruptions can shoot minerals into the air that later fall into oceans, nourishing marine life far away. ✨
#lithosphere⚡#atmosphere⚡#hydrosphere⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 When huge dust storms sweep across deserts, fine particles from the lithosphere reach the atmosphere, circle the globe, and even fertilize distant rainforests—linking Earth’s spheres in invisible ways. ✨
#lithosphere⚡#atmosphere⚡#hydrosphere⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 A single major volcanic eruption links all of Earth’s spheres—rock and magma from the lithosphere, gas and ash in the atmosphere, water vapor in the hydrosphere, and rapid changes in the biosphere. ✨
#lithosphere⚡#atmosphere⚡#hydrosphere⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The hydrosphere holds less than 0.01% of Earth's water in rivers and lakes, while most is locked in glaciers, ice caps, or underground. These hidden reserves link all of Earth’s spheres. ✨
#hydrosphere⚡#lithosphere⚡#biosphere⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The deepest part of the ocean, the Mariana Trench, reaches nearly 11,000 meters below sea level. Here, the hydrosphere, lithosphere, and biosphere all meet in extreme conditions. ✨
#hydrosphere⚡#lithosphere⚡#biosphere⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 The deepest point on land, the Dead Sea Depression, lies about 430 meters below sea level, linking the lithosphere, atmosphere, hydrosphere, and biosphere in an extreme environment for life. ✨
#lithosphere⚡#hydrosphere⚡#biosphere⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 At the bottom of Antarctica’s ice lies a vast liquid lake called Lake Vostok, sealed under 4 kilometers of ice. This hidden hydrosphere supports unique life forms adapted to total darkness. ✨
#hydrosphere⚡#Antarctica⚡#secrets⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍