Как работает функция 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 Costa Rica, the golden orb-weaver spider spins silk that glows bright gold in sunlight. This strong, shimmering web attracts pollinating insects while reflecting UV light, making it both a trap and a natural artwork. ✨
#spiders⚡#biodiversity⚡#adaptation
👉subscribe Interesting Planet
🌎 Peacock spiders from Australia show off bold, iridescent colors during their unique courtship dances. Males raise flaps on their abdomen that resemble tiny rainbows to attract females. Over 80 species have been identified, each with distinct colors and patterns. ✨
#animals⚡#camouflage⚡#spiders
👉subscribe Interesting Planet
🌎 A single strand of spider silk is so thin and strong that, if scaled up, it could stop a speeding jet airliner. Spider silk’s unique proteins give it greater tensile strength than steel, making it a model for future lightweight materials. ✨
#spiders⚡#biomaterials⚡#engineering
👉subscribe Interesting Planet
🌎 The silk of the Darwin's bark spider, found in Madagascar, is the toughest biological material known—over 10 times stronger than Kevlar used in bulletproof vests. ✨
#spiders⚡#materials⚡#Madagascar
👉subscribe Interesting Planet
Arachnophobia or the fear of spiders is the oldest and most common phobia in the Western culture. The word Arachnophobia is derived from the Greek word ‘arachne’ meaning spiders.
🕷🕸
[Learn more]
@googlefactss
#spiders#fear#HumanMind
The world’s biggest spiderweb—home to 111,000+ spiders— is found in the Cave of Sulphur on the Albanian–Greek border. Two common species built a massive colonial cobweb in a permanently dark zone—the first record of cooperative web-building at this scale. Researchers call for preservation and are preparing follow-up studies. 🕷️🕸️🌍🇦🇱🇬🇷
[Read more here]
@googlefactss
#Nature#Discovery#Spiders#Conservation
Jumping spiders are small spiders in the Salticidae family. They have four pairs of eyes, with large front eyes for hunting and navigation. They do not build webs to catch prey. They hunt by stalking and leaping on insects. They use silk as a safety line when they jump. Some species are kept as pets and are easy to care for.
🕷️🌿🎯
[Read more]
@googlefactss
#Spiders#JumpingSpider#Salticidae#Nature#Pets