Как работает функция 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
🚀 To celebrate the partnership with @AEON_Commuinty, the leading crypto payment framework, built for AI to drive intelligent, automated payments across Web3 and simplify how crypto works in real life, we're hosting a GIVEAWAY! 🎉Total $700 Up For Grabs!
⏰May 1st, 10:00 AM - May 20th, 10:00 AM (UTC)
1️⃣$200 raffle for qualified #Galxe participants
2️⃣$500 rewards via AEON Pay for TOP and FCFS consumers
Consume $UXLINK to cover daily expenses (Each transaction must over $5).
👀Stay tuned for the upcoming announcement! In the meantime, feel free to take a sneak peek here 👉https://t.me/aeon_pay_bot
The competition is heating up, and it's time to take your skills to the next level in our #TON Capital #Galxe Campaign!⚡️
With more tasks, bigger rewards, and an even tougher playing field, the challenge is yours to conquer.
💪 Complete missions, accumulate points, and rise to the top of the leaderboards for your chance to claim extraordinary rewards. From challenges and quizzes to community actions, every task pushes you closer to victory.
🎁 The Best Will Be Rewarded:
🏆A $1000 USDT prize pool awaits the Lucky 100 on our Galxe campaign leaderboard
🏅Exclusive badges for the Lucky 500 contributors ( Galxe Explorer + Guaranteed Whitelist)
🎯Access to the Season 1 Expedition Grand Prize, worth up to $50,000 and 88.8m $TONCAP!
Join TON Capital Galxe Campaign -- https://app.galxe.com/quest/SAw9YJRiY3VF2oevPJpa3K/GCWPWtKwCQ
Show us what you’ve got and seize your opportunity to be part of something great in the world of TON and Web3.
⚡️The future is yours to shape!
🎉 Solana Leveling #Airdrop on #Galxe🎉
We’re giving away $5 to 10 lucky winners 💸
✅ Complete simple social tasks
✅ Join the Solana Leveling community
✅ Stay updated with the best Solana insights
👉 Enter here:https://app.galxe.com/quest/AygxpG3nDj4VfTNkmsTrpN/GCUxJt6zNX
🆕 Galxe now fully supports #TokenPocket login!
👉https://extension.tokenpocket.pro/
Galxe is the leading platform for building the Web3 community.
🔥Follow TokenPocket Space and Get Ready for the #TokenPocketChristmas on #Galxe!
👉https://galxe.com/TokenPocket
Details:
👉https://twitter.com/Galxe/status/1729918366012600584
👉https://twitter.com/TokenPocket_TP/status/1730068829311774726
⚡️Electra launches a quest on Galxe!
We are pleased to announce that🚀Electra launches an exciting $ELT token reward campaign on the #Galxe platform!
This means that Airdrop is just around the corner!
🏆
💵 As part of this campaign, you have the opportunity not only to earn $ELT tokens, but also to participate in prize draws in $USDT, unique NFTs and tokens from top partners🤝Electra!
Complete quests, follow the news and get ready for the $ELT airdrop!
➡️Take part in the campaign
#Electra#Airdrop#DeFi#Web3
Become an APTOS and SUI supporter and reach new peaks⛰
Go to Galxe 👇
https://galxe.com/apstation/campaign/GCLYeU42e1…
#Aptos#Galxe#AptosEcosystem#Sui#SuiEcosystem
https://twitter.com/CetusProtocol/status/1621413895578726400?s=20&t=idtvF7UcG6zXWiw2NhUUdA
@everyone
🔥Airdrop – Empeiria x Leap Wallet ✅
💠Reward:Empe Micro Node (worth $50) – Grants access to EMPE token staking rewards. Claiming starts after TGE.
☀️Airdrop Link :- Click Here
⚙️How to Participate?
♦️Jointheevent on Galxe
♦️Complete all listed quests
♦️Connect your wallet & verify tasks
♦️Secure yourEmpe Micro Node reward
📌Note:Limited-time event – don’t miss your chance to get early staking access with Empeiria
®Note - Please do your own research (DYOR) before joining to any airdrops project, also airdrop is 100% free. Don't send any fee or penny for receiving airdrop tokens.
#Empeiria#LeapWallet#Galxe#Airdropcomic#CryptoRewards#Web3