Как работает функция 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
When paying respects this Qing Ming, let’s continue to be socially responsible and observe #SafeDistancing measures. As crowds are expected at Choa Chu Kang Cemetery and government-managed columbaria, visitors are advised to send 2 representatives per household (with not more than 8 pax per group). The opening hours will be extended to 24-hours, with effect from 20 Mar until 18 Apr 2021.
Visitors driving to Mandai Columbarium during peak days will also be required to book an appointment. Visit www.nea.gov.sg/qingming2021 for more information.
From 12 Sep 2020, weekend visitors to the 4 popular markets (Geylang Serai Market, Chong Pang Market, Block 20/21 Marsiling Lane, and Block 505 Jurong West Street 52) will not be subject to the odd/even date entry restriction. However, the caps on the number of patrons allowed in the market at any one time will still be in place, to ensure sufficient #SafeDistancing. More information available at https://go.gov.sg/nea-lifting-entry-restriction-markets-12sep
During Phase 2, you may leave your home to smoke, but do so in an area where smoking is not prohibited, and observe #SafeDistancing requirements. To protect yourself and others around you, do put your mask back on as soon as you have finished smoking. From 19 Jun, Designated Smoking Areas along the Orchard Road No Smoking Zone can re-open with safe distancing measures. Smoking corners beyond the Orchard Road No Smoking Zone, can also re-open with the necessary safe distancing measures in place. www.nea.gov.sg/post-circuit-breaker-measures
From 22 Apr 2020, access to 4 popular markets will be restricted based on the last digit of patrons’ NRIC or FIN numbers, to ensure effective #SafeDistancing and safeguard public health. Patrons with NRIC/FIN ending with:
- an even last digit (0, 2, 4, 6, 8) can only visit on the even dates of the month
- an odd last digit (1, 3, 5, 7, 9) can only visit on the odd dates of the month
These 4 markets are Geylang Serai Market, Block 104/105 Yishun Ring Road (Chong Pang Market), Block 20/21 Marsiling Lane Market, and Block 505 Jurong West Street 52 Market. More information available at www.facebook.com/NEASingapore/posts/2589759427912055
If your parents or older relatives do their grocery shopping at these 4 popular markets, do share the guide (available in 4 different languages) with them! Download a copy from https://www.facebook.com/NEASingapore/posts/2590540227833975
Dine-in at #OurHawkerCentres resumes from 19 Jun! Whilst you may be excited to meet with your friends, limit the group to 5 people or less and continue to observe #SafeDistancing measures – use unmarked seats/tables, keep 1 metre apart from others, and only remove your masks when eating.
At our markets, continue to stand within the boxes marked on the floor, to maintain a safe distance. Access to the 4 popular markets will continue to be restricted based on the last digit of your identification number. More information available at www.nea.gov.sg/media/news/advisories/index/safe-management-measures-in-phase-2-at-hawker-centres-and-markets
Need your essentials? In addition to wearing a mask to buy essentials at the supermarket, schedule your grocery run on a weekday and avoid the peak periods, or opt for delivery instead. Let’s take #SafeDistancing seriously, and work together to stop the spread of COVID-19. #SGUnited
Planning dinner with your friends? Due to #SafeDistancing, there may be limited seating capacity at many places, so call in advance to make reservations first. Otherwise, opt for takeaway (bring your own containers!) or delivery 😊#SGUnited#FightCOVID19
#SafeDistancing applies everywhere – even when choosing fish and vegetables at the markets! If you have elderly neighbours or family members, help them with their marketing instead so that they can #StayHome and stay safe. #SGUnited
Only sit on seats without markings when dining in at #OurHawkerCentres to maintain #SafeDistancing. If the seating capacity is limited, #BringYourOwn clean containers and choose to take-out instead. Let’s unite to #FightCOVID19 together! 💪#SGUnited
Let’s remember to stay at least a metre apart from each other. We wouldn’t want all the effort and resources of the past few months to go to waste. Dining in at #OurHawkerCentres? Let’s not forget to #ReturnOurTrays and #BinOurTissues after enjoying the meal! #SGUnited#SafeDistancing#FightCOVID19