Как работает функция 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
🚀 Great Start of SLEX Launchpad!🎉
⚡️The first day of SLEX Launchpad sales was a huge success with over 37,78% of allocations sold out! Whitelist participants, you have a last chance to be part of this exclusive event, but hurry up as allocation actively decreases with high users demand📈
🗓️The sale ends tomorrow, February 17th. Don't miss the last chance to take exclusive advantages of SLEX Launchpad.
#SLEXLaunchpad#LastChance#CryptoSale
Website| Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter
🎉Amazing Success of the first SLEX Launchpad! 🚀
📈A huge thanks to all participants who joined the first SLEX Launchpad! Your participation made it an outstanding success!
🔥
🤝Don't miss out on future opportunities - follow us on our social channels. Here's you can find more interesting updates and events soon:
Website| Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter
#SLEXLaunchpad#SLEX#SLEXSale#StayTuned
🚀The Time Is UP: Today is the First Day of SLEX Launchpad Sale! ☄️
⚡️The wait is over! The first SLEX Launchpad officially starts today, February 15th at 12:00 UTC, after our Whitelist successfully closed with over 4000 participants. This marks the beginning of exceptional earning opportunities for our community🎉
🔥Premier Project Access: SLEX token holders, get ready for exclusive access to Tier-1 crypto projects. These handpicked projects offer a rare chance to invest in potentially profitable tokens.
💰Maximize Your Earnings: participate in the Launchpad to unlock staking rewards and additional trading benefits on SLEX Exchange.
📅 Important Reminder for Whitelist Members:
👀Due to the fact that token allocation and the time of the sale are limited, we recommend to deposit funds on your account in advance.
✍🏻If you did not create an account on SLEX yet, make sure that you create one under the email you specified in the Whitelist application form to be able to participate in token sale.
#SLEX#LaunchpadLive#SLEXTokens#SLEXLaunchpad#SLEXWhitelist
Website| Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter
🚀Let the Sale Begin: The first SLEX Launchpad for 4000 Participants Starts on February 15th! 🎉
⚡️We are thrilled to announce that the Whitelist on SLEX has been successfully closed with more than 4000 participants. And now we are at the finish line because it's only two days until the launch of the much-anticipated SLEX Launchpad!⚡️
📈Mark your calendars and prepare to join SLEX Launchpad to get access to exceptional ways of earning:
🔥Access to Tier-1 Projects: SLEX token holders will gain exclusive access to Tier-1 projects, offering a gateway to the most promising and innovative crypto projects.
💰Staking Rewards and Trading Benefits: Token holders can get rewards from staking and additional trading bonuses at SLEX Exchange.
📅 If you are a Whitelist member check out email for more details and instructions about participation in the first SLEX Launchpad!
#SLEX#LaunchpadAnnouncement#CryptoInnovation#SLEXTokens#TradingBenefits#SLEXLaunchpad#SLEXWhitelist
Website| Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter
🚨 Last Chance: SLEX Whitelist is Coming to an End! ⏳
🔥Time is ticking! The exclusive opportunity to join the SLEX Whitelist only for the community is nearing its end on February 1st. This is an exceptional way to get early access to a limited allocation of SLEX Coins before Public listing!
🤝Take your last chance and join SLEX Whitelist: slex.io/launchpad/slex
🤔We've also got an exciting way to show you the ambitious and in-depth look at SLEX plans and vision on Binance:www.binance.com/en-AE/feed/post/1058789
#SLEXWhitelist#SLEXExchange#JoinNow#BinanceArticle#SLEXCoin#PublicSale#SLEXLaunchpad
Website| Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter