Как работает функция 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
🌎 Astronomers have detected rapid radio bursts—millisecond-long signals from distant space. These intense pulses hint at extreme events, like collapsing stars or magnetars, yet their exact origin remains one of space’s most intriguing mysteries. ✨
#astronomy⚡#space⚡#mysteries
👉subscribe Interesting Planet
🌎 Space isn’t silent—astronomers have recorded eerie “whistles” and “choruses” from planets like Jupiter. These radio waves, caused by charged particles moving through magnetic fields, are transformed into sound waves we can hear when played back on Earth. The haunting tunes of space reveal hidden cosmic activity all around us. ✨
#astronomy⚡#space⚡#mysteries
👉subscribe Interesting Planet
🌎 Off the coast of Scotland, the Orkney Islands’ Tomb of the Eagles is a Stone Age burial site containing over 16,000 human and animal bones. Archaeologists discovered that the tomb, built around 3150 BCE, was used for more than 800 years before being sealed. ✨
#archaeology⚡#mysteries⚡#prehistory
👉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
🌎 On the border between Egypt and Sudan lies Bir Tawil, a peculiar territory claimed by neither country. Due to a mapping oddity, Bir Tawil is one of the world’s rare “unclaimed” lands, standing as a real-life no man’s land on modern maps. ✨
#geography⚡#borders⚡#mysteries
👉subscribe Interesting Planet
🌎 The Brandberg Mountain in Namibia is famous for its mysterious White Lady rock painting, estimated to be at least 2,000 years old. Archaeologists debate whether the figure represents a woman, man, or ritual dancer, and the exact meaning of the painting remains unclear. The site contains over 45,000 individual rock paintings. ✨
#archaeology⚡#Namibia⚡#mysteries
👉subscribe Interesting Planet
👉more Channels
🌎 The underwater Stone Circles of Lake Michigan were discovered in 2007 by archaeologists using sonar. The stones are arranged in a circle about 12 meters below the surface. One stone features a carving resembling a mastodon, hinting at a possible age of over 10,000 years. ✨
#mysteries⚡#archaeology⚡#lake
👉subscribe Interesting Planet
👉more Channels
🌎 Bolshoi Zayatsky Island in Russia’s White Sea features hundreds of mysterious stone labyrinths, or “Babylons,” built by unknown people. Most date back 2,000–3,000 years. Archaeologists suggest they served ritual or astronomical purposes, but their exact function remains unproven. ✨
#mysteries⚡#archaeology⚡#Russia
👉subscribe Interesting Planet
👉more Channels
🌎 The ancient city of Hattusa, capital of the Hittite Empire, features massive stone walls, elaborate gates, and mysterious underground tunnels. Archaeologists found cuneiform tablets here describing treaties, religions, and daily life. The site was abandoned around 1200 BCE for unknown reasons. ✨
#Hittite⚡#archaeology⚡#mysteries
👉subscribe Interesting Planet
👉more Channels
🌎 The disappearance of 20,000-year-old giant cave art in Chauvet Cave, France, puzzles scientists. Some images faded, while others vanished completely, possibly due to natural mineral changes, humidity, or hidden collapses in the limestone walls. The cave holds more than 1,000 preserved prehistoric paintings and engravings. ✨
#archaeology⚡#mysteries⚡#art
👉subscribe Interesting Planet
👉more Channels
🌎 Deep in the Ural Mountains of Russia, the remote plateau called Manpupuner features seven enormous stone pillars, each up to 42 meters tall. These ancient rock formations, shaped by frost and wind over millions of years, were considered sacred by Indigenous Mansi people. The pillars’ unique shapes and mysterious origin make them one of Russia’s least accessible and most enigmatic natural monuments. ✨
#geology⚡#mysteries⚡#Russia
👉subscribe Interesting Planet