Как работает функция 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
🐈⬛DEAL OF THE WEEK
🐈⬛
🐈⬛Heel Hook The World: The Complete Beginners Guide by Heath Pedigo and Jacob Couch
🐈⬛
$197
🐈⬛$9.99
🐈⬛
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱📱
💰Submeta FOR FREE
👑MasterClass
✈️@bjjfanaticsinstructionals
#DealOfTheWeek#HeathPedigo
🐈⬛Buy
🐈⬛
🐈⬛DEAL OF THE WEEK
🐈⬛
🐈⬛Daisy Fresh WHITE BELT Wrestling Curriculum by Alejandro Wajner and Heath Pedigo
🐈⬛
$197
🐈⬛$9.99
🐈⬛
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱📱
💰Submeta FOR FREE
👑MasterClass
✈️@bjjfanaticsinstructionals
#DealOfTheWeek#HeathPedigo
🐈⬛Buy
🐈⬛
🔥NEW RELEASE🔥
😁The Trip Throw Dilemma By Michael Pixley And Heath Pedigo😁
➡️Unlock the secrets of effective takedowns with "The Trip Throw Dilemma," a groundbreaking Brazilian Jiu-Jitsu instructional by renowned coaches Michael Pixley and Heath Pedigo. As the founder of the famed Daisy Fresh team, Heath has shaped some of the best talent in the world, while Michael brings his expertise as a former NCAA and NAIA champion wrestler to the mat.
➡️This instructional dives deep into the intricacies of trip throws, providing you with the tools and techniques to elevate your game.
$197😍$14.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
🌈UFC Picks
👑MasterClass
✈️@bjjfanaticsinstructionals
#MichaelPixley#HeathPedigo#NoGi#Takedowns
💁♀️Buy
💁♀️
🔥NEW RELEASE🔥
😁Geekological Approach Introduction to Jiu Jitsu Daisy Fresh Style by Heath Pedigo😁
➡️Unlock the hidden systems behind one of the most dominant teams in jiu jitsu today. Heath Pedigo, the mastermind behind the Daisy Fresh BJJ phenomenon, unveils his revolutionary Geekological Approach – a methodical, principle-based system designed to fast-track your jiu jitsu from white to purple belt.
➡️This isn't just another fundamentals course. This is a battle-tested blueprint used to build the winningest lower belt team in the sport, straight from the gritty mats of Mt. Vernon, Illinois. Heath's style is raw, effective, and unapologetically structured – designed to produce measurable results through simple, repeatable training "games."
$197😍$14.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
👑MasterClass
✈️@bjjfanaticsinstructionals
#HeathPedigo#Fundamentals#Gi#DaisyFresh
💁♀️Buy
💁♀️