Как работает функция 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
🇺🇸#LosAngeles. Wild teens ransack Chevron store in Lincoln Heights in broad daylight.
Another SoCal store is taken over by rampaging teens racksacking aisles, grabbing whatever they can. This time, a Lincoln Heights Chevron station is hit. The frustrated store managers who want police to do more to stop the takeovers.
Follow us -> LiveLeak
Please do not curse the victims of the American fires. There are many innocent civilians and pro-Palestinian people. Those elites had already fled before the fires came.
#LosAngeles
This is absolutely disgusting and heartbreaking.
Homeless addicts on Skid Row in LA are using innocent dogs to test their drugs for fentanyl. These poor animals are being fed deadly substances, abused, neglected, sold for drugs, and thrown away like trash.
Volunteers from Starts With One Today are risking their lives to rescue these dogs with zero support from the city.
How has Mayor Karen Bass and LA leadership let this horror continue? Animals are suffering and dying in plain sight while officials do nothing.
This is pure cruelty. Where is the outrage? Where is the action?
#SaveSkidRowDogs#AnimalAbuse#LosAngeles
🔹👉🏻@SherriTenpenny
PERFECT RING FORMED OVER LOS ANGELES
This appeared high above L.A. just after dusk.
A bright linear trail stretched across the sky — and around it, a smooth circular arc expanded and held its shape.
The symmetry is what stands out.
A straight line through the center.
A clean curve wrapping around it.
It lingered long enough for people across the city to stop and stare.
Los Angeles, California.
Did you catch this from where you are?
MrMBB333
👇 Drop your city.
#MrMBB333#SkyWatch#LosAngeles
#Wildfires ravage #California, leaving 5 people dead and over 27,000 acres burned. #LosAngeles Authorities warned casualties may rise as the fires remain uncontained.
USA Major League Soccer🇺🇸
2026-04-19 23:00 UTC
Los Angeles FC vs. San Jose Earthquakes
Predicted outcome: Los Angeles FC❌
Predicted score: 2:1
Actual: San Jose Earthquakes 1:4
#LosAngeles#SanJoseEarthquakes
#Football#USAMLS
As #LosAngeles burns and #firefighters face a severe water crisis, criticism is mounting against #billionaires Stewart and Lynda #Resnick, whose $13B agricultural empire consumes more water than LA and SF combined.
#PalisadesWildFire
USA Major League Soccer🇺🇸
2026-05-10 20:30 UTC
New York City FC vs. Columbus Crew
Predicted outcome: New York City FC✅
Predicted score: 3:2
Actual: New York City FC 3:0
#NewYorkCity#ColumbusCrew
2026-05-10 23:00 UTC
Minnesota United FC vs. Austin
Predicted outcome: Minnesota United FC❌
Predicted score: 2:1
Actual: Draw 2:2
#MinnesotaUnited#Austin
2026-05-11 01:00 UTC
Los Angeles FC vs. Houston Dynamo
Predicted outcome: Los Angeles FC❌
Predicted score: 2:1
Actual: Houston Dynamo 1:4
#LosAngeles#HoustonDynamo
#Football#USAMLS