Как работает функция 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
🚨CyberCharge discount sale ends, price back to $198! 🚨
Thanks to all our supporters — nearly 10,000 devices shipped globally 🌎
More users are joining the Web3 journey of earning while charging ⚡️
CyberCharge is becoming the 1 choice for #DePIN earners.
🔥Follow us for occasional limited-time $148 promotions!
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
TWITTER SPACE!!
🕊
🚀 Join us on Aug 20th at 12 PM UTC for a Twitter Space on the #DePIN wave!
📚Topic: Can the Bitcoin ecosystem become the new battleground in the DePIN wave?
📍https://twitter.com/i/spaces/1DXxydzBZVNJM
👥 Panel:
- @CyberChargeJoe
- @MasterOfCoins from MyCoralApp
- @MelosBoom
- @Dr_lovelyman from Tap protocol
- @YProselkov from WebKey01
Don't miss it! CyberCharge
Like👍, Retweet🔁, Comment
Link to the tweet!
⚡️CyberCharge – The one charger to power them all!
🔋Revolutionize your energy needs with cutting-edge technology designed for the future.
👉cybercharge.org looking forward to more updates on the #DePIN revolution in energy.
Like👍, Retweet🔁, Comment
Link to the tweet!
We are thrilled to partner with SrcAi_Official!
🚗 SRC ai is an AI-powered Web3 app that monetizes routine driving data, transforming driving habits into recorded and rewarded activities. Monetize your driving data and contribute to the advancement of autonomous tech with SRC ai.
🔋 CyberCharge is the next-generation global power matching protocol and the world's first #DePIN C2E network focused on charging and mining.
We will drive AI and blockchain growth together while exploring new opportunities.
Like👍, Retweet🔁, Comment
Link to the tweet!
💡CyberCharge is the world's first smart charger that combines #Web3 and #DePIN to turn every charge into a digital currency reward while supporting the decentralized Web3 network.
We've got even more rewards for you in Miniapp, where you can draw free treasure chests for tokens like $SOL, $TON, and more!
Let's unleash the full potential of the Cybercharge ecosystem!
After completing all the @taskonxyz 50 winners will receive an equal amount of gems with a total value of $200!
Join: https://taskon.xyz/quest/404918461
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
⚡️CyberCharge is proud to sponsor the R3alWorld Summit 2024 at #TOKEN2049 .
🤝Join us in Singapore as we showcase the future of decentralized energy solutions and participate in key discussions on the #DePIN industry
Like👍, Retweet🔵, Comment
Link to Tweet
🎁Join our Airdrop Event
Link to MiniApp
Link to IoTeX tweet:
The Future of DePIN: Energy at its Core
⚙️DePIN is transforming Web3, enhancing energy security and adaptability with real-time distribution and monitoring.
⚡️In Low-Voltage transmission, it boosts safety, responsiveness, and efficiency.
#CyberCharge#DePIN
Like👍, Retweet🔵, Comment
Link to Tweet
🤖Join Bot🐣X (Twitter)✉️Chat
Don't miss out #CyberCharge Charger 🥳
Check out the tweet below to learn how to enter the biggest #DePIN giveaway IN HISTORY. 👇
Click Here
Like👍, Retweet🔵, Comment
Link to Tweet
🎁Join our Airdrop Event
Link to MiniApp
🤝#CyberCharge is teaming up with @Weaver_Labs, leaders in Telecom and #DePIN innovation!
📡Weaver Labs is transforming the telecom industry with blockchain-powered decentralization via Cell-Stack, making connectivity accessible for everyone!
🔋CyberCharge, the world's first DePIN C2E network, combines charging and mining, powered by a global weak-voltage power matching protocol.
Like👍, Retweet🔵, Comment
Link to Tweet
🎁Join our Airdrop Event
Link to MiniApp
🚀#CyberCharge is kicking off its Global Tour at @token2049 Singapore!
📍First stop: Marina Bay Sands, 18-19 September 2024.
🤝Come visit our Main Event Booth M126 (Level 4) and experience the future of #DePIN innovations firsthand
Like👍, Retweet🔵, Comment
Link to Tweet
🎁Join our Airdrop Event
Link to MiniApp