Как работает функция 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
📖Title : The Return of the King
✍️Author : J.R.R. Tolkien
⭐️Rating : 4.58/5 (Goodreads)
📆Published : Oct 20, 1955
————————————————
Summary:In The Return of the King, the final volume of J.R.R. Tolkien’s The Lord of the Rings, the forces of Gondor and Rohan prepare for the ultimate battle against Sauron. Aragorn embraces his destiny as the true king, rallying allies and marching to the Black Gate as a diversion. Meanwhile, Frodo and Sam struggle through Mordor to destroy the One Ring in Mount Doom. Gollum’s obsession leads to his and the Ring’s destruction, ending Sauron’s reign. Peace returns to Middle-earth, Aragorn is crowned, and the hobbits return to a changed Shire. Frodo later departs with the Elves to the Undying Lands.
————————————————
#fantasy#fiction#classics#adventure#novels#LOTR@Bookslibraryofficial@free_novellas@thesciencelabs
📖Title : The Two Towers
✍️Author : J.R.R. Tolkien
⭐️Rating : 4.50/5 (Goodreads)
📆Published : Nov 11, 1954
————————————————
Summary:In The Two Towers, the Fellowship is broken. Frodo and Sam continue their perilous journey to Mordor to destroy the One Ring, joined reluctantly by the treacherous yet pitiful Gollum, who becomes both guide and threat. Meanwhile, Aragorn, Legolas, and Gimli pursue the Uruk-hai who have captured Merry and Pippin. Their paths lead to the war-torn kingdom of Rohan, where they aid King Théoden against the forces of Saruman. As darkness spreads and war looms, alliances are tested and hope flickers. The story deepens the moral complexity of the quest, showing how power corrupts and loyalty defines true heroism.
————————————————
#fantasy#fiction#classics#adventure#novels#LOTR@Bookslibraryofficial@free_novellas@thesciencelabs