Как работает функция 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
[Sent by Gov.sg – 17 Feb]
SG Clean
- COVID-19 is transmitted primarily through droplets. To fight this outbreak, we need to look after our personal hygiene, AND keep Singapore clean.
- A clean environment will help stop community transmission of COVID-19
7 good habits
1. Keep premises clean and pest-free
2. Return trays, keep tables clean
3. Keep toilets clean and dry
4. Wash hands regularly with soap
5. Take temperature, see doctor if unwell, stay home
6. Use tissue when sneezing or coughing
7. Bin litter and soiled tissue
NEA stepping up:
- Inspection of public toilets and other public places
- Enforcement against spitting and littering
- Adoption of SG Clean quality mark, to ensure high level of cleanliness
More on #SGClean: go.gov.sg/sgclean
More hygiene tips: go.gov.sg/getserious
More than 5,000 premises have been certified #SGClean since the campaign launch on 16 Feb 2020!
But what does this mean? Premises with the SG Clean quality mark have high levels of cleaning and hygiene standards. Go to sgclean.gov.sg for a list of places that are certified SG Clean.
#DidYouKnow that Chomp Chomp Food Centre’s unique name originated from its Teochew name, Tiong Tiong, which means loyalty and righteousness?
If you’ve visited Chomp Chomp recently, you may have seen the SG Clean quality mark signalling the hawker centre’s high level of cleaning and hygiene standards. The full list of certified SG Clean places is available at sgclean.gov.sg
#SGClean#OurHawkerCentres
Are we practising #GoodHygieneHabits when we’re out and about? From washing our hands regularly to using a serving spoon and avoiding double-dipping, let’s not forget these practices when dining with family and friends. #SGClean
Meet our SG Clean Ambassadors! Sharing a common passion to make #SGClean a way of life, our #SGCleanAmbassadors will help drive the adoption of good personal habits and social norms.
They will encourage patrons to return their trays and keep tables clean, and guide them on safe distancing measures to #FightCOVID19 and other infectious diseases. Interested to join the SG Clean Ambassadors Network? Sign up at http://go.gov.sg/sgcleanambassadors
“We are the first line of defence in ensuring that our patrons dine with peace of mind. We have intensified our cleaning efforts to ensure the cleanliness of the toilets, food trays, cutlery, tables and chairs. One major change to our daily work is the use of four different cloths, each for a different purpose. With these enhanced measures, we hope to reassure the public and encourage them to continue dining here.” – Mr Deji Pravin, Nick Cleaning Services Pte Ltd, Hawker Centre @ Our Tampines Hub
#FightCOVID19#SGClean#SGUnited#SingaporeTogether
Heading out for lunch at your favourite hawker centre, coffeeshop or food court? Remember to put your used tissues where they belong! #BinUsedTissue#CleanYourTable#SGClean
We are all looking forward to dining in again at our favourite places. Let’s not forget good dining habits at #OurHawkerCentres to mitigate the spread of COVID-19! #BinOurTissues & #ReturnOurTrays, to keep the table clean for the next user and reduce the risk of disease transmission to cleaners and other members of the public. Eat from your tray, and don’t leave behind soiled tissues or wet wipes on dining tables. #FightCOVID19#SGClean
We continue to press on in the fight against the COVID-19! NEA has been providing guidance to operators of food establishments, including stallholders at #OurHawkerCentres, to maintain high standards of hygiene and cleanliness to safeguard public health.
You can do your part by practising the 7 Habits of Good Public Hygiene! Together we can overcome!
#FightCOVID19#SGClean#SingaporeTogether#SGUnited
https://youtu.be/t19szcAGw-U
Don’t leave your used tissues or wet wipes behind when dining at #OurHawkerCentres! It is important to dispose of used tissues or wet wipes which can be highly contaminated, to #FightCOVID19, especially as we resume our activities gradually.
From 19 Jun when dining-in resumes, Safe Distancing Ambassadors at hawker centres and coffeeshops will be on hand to remind patrons to be socially responsible and observe personal hygiene. Let’s all do our part to keep ourselves and those around us safe. https://go.gov.sg/nea17jun20-hygieneathcs-toilets
#BinOurTissues#ReturnOurTrays#SGClean#KeepSGClean