Как работает функция 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
🌎 In ancient Chavín culture of Peru, intricate stone “pututu” conch trumpets echoed across ceremonial plazas. These natural shell horns carried sound up to a kilometer, uniting crowds during old rituals and feasts with their deep, haunting music. ✨
#history⚡#sound⚡#archaeology
👉subscribe Interesting Planet
🌎 The "Bloop" is one of the loudest underwater sounds ever recorded. Detected by NOAA hydrophones in 1997, this low-frequency noise was picked up over 5,000 kilometers apart. Scientists later identified melting icebergs as the likely source, not a sea creature or submarine volcano. ✨
#ocean⚡#sound⚡#mysteries
👉subscribe Interesting Planet
👉more Channels
🌎 Mysterious low-frequency sounds known as "The Upsweep" have been picked up by underwater microphones in the Pacific Ocean since 1991. This persistent sound rises and falls in pitch, lasts several seconds, and is strongest in spring and autumn. Its source remains unidentified, but some researchers suggest volcanic activity near the origin point may be involved. ✨
#ocean⚡#mysteries⚡#sound
👉subscribe Interesting Planet
👉more Channels
#sound
#неКуКураж_круче
#КультМедиа
Профессиональная команда дикторов возьмётся за озвучку любого ролика.
Каз/Рус/Муж/Жен.
От литературных текстов до делового стиля, портфолио предоставим.
Опыт озвучки: аудиокниги, анонсы телеканалов, имиджевые ролики крупных компаний и городов и проч.
wa/tg: +7 777 240 22 42
t.me/cult_media
🌎 The “singing” sands of select deserts produce eerie musical tones when walked on or disturbed. This haunting sound comes from millions of perfectly sized sand grains rubbing together and vibrating in harmony—nature’s own desert orchestra! ✨
#geology⚡#sound⚡#phenomenon
👉subscribe Interesting Planet
🌎 Strange cosmic "whistlers" recorded by satellites are caused by lightning on Earth. These radio signals travel along Earth's magnetic field, bounce off space, and return as high-pitched, descending tones—lasting less than a second. Some whistlers have been traced over thousands of kilometers from their original lightning strike. ✨
#space⚡#sound⚡#lightning
👉subscribe Interesting Planet
👉more Channels
🌎 Earth’s Schumann resonances are a set of naturally occurring, low-frequency electromagnetic waves circling the globe between the ground and the ionosphere. These “global hums” are mainly generated by lightning and pulse mostly at 7.83 Hz, serving as a natural radio background measured by scientists worldwide. ✨
#space⚡#sound⚡#atmosphere
👉subscribe Interesting Planet
👉more Channels
🌎 Some of the loudest natural sounds ever recorded in the ocean come from snapping shrimp, which use their oversized claw to shoot a high-speed bubble. When the bubble collapses, it creates a sound reaching 210 decibels—louder than a gunshot—and can stun small prey nearby. ✨
#ocean⚡#animal⚡#sound
👉subscribe Interesting Planet
👉more Channels
🌎 Jupiter’s magnetosphere produces “chorus” radio waves—sounds like twinkling or whistling—detected by NASA spacecraft. These signals are created by energetic electrons moving along the planet’s powerful magnetic field. The Juno probe recorded these plasma waves in 2016. ✨
#Jupiter⚡#space⚡#sound
👉subscribe Interesting Planet
👉more Channels
🌎 The Voyager 1 spacecraft captured “plasma wave” sounds as it entered interstellar space in 2012. These sounds are actually electromagnetic vibrations in space, converted into audio by NASA scientists. The pitch and intensity help scientists measure the density of charged particles beyond our Solar System. ✨
#Voyager⚡#space⚡#sound
👉subscribe Interesting Planet
👉more Channels