TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #397 · 12 ное.

Использование Pydantic сегодня стало нормой, и это правильно. Но иногда на ревью вижу, что используют его не всегда корректно. Например, метод BaseModel.model_dump() по умолчанию не преобразует стандартные типы, такие как datetime, UUID или Decimal, в простой сериализуемый для JSON вид. Тогда пишут кастмоный сериализатор для этих типов чтобы функция json.dump() не падала с ошибкой. import uuid from datetime import datetime from decimal import Decimal from uuid import UUID from pydantic import BaseModel class MyModel(BaseModel): id: UUID date: datetime value: Decimal obj = MyModel( id=uuid.uuid4(), date=datetime.now(), value='1.23' ) print(obj.model_dump()) # не подходит для json.dump # { # 'id': UUID('4f8c1bc4-25fd-40cd-9dbe-2c73639b0dc1'), # 'date': datetime.datetime(2025, 12, 12, 12, 12, 12, 111111), # 'value': Decimal('1.23') # } # добавляем свой кастомный сериализатор json.dumps(obj.model_dump(), cls=MySerializer) # { # 'id': '4f8c1bc4-25fd-40cd-9dbe-2c73639b0dc1', # 'date': '2025-12-12T12:12:12.111111', # 'value': '1.23' # } В данном случае класс MySerializer обрабатывает datetime, UUID и Decimal. Например так: class MySerializer(json.JSONEncoder): def default(self, o): if isinstance(o, Decimal): return str(o) elif isinstance(o, datetime): return o.isoformat() elif isinstance(o, UUID): return str(o) return super().default(o) Специально для тех, кто всё еще так делает - в этом нет необходимости! Pydantic может это сделать сам, просто нужно добавить параметр mode="json". json.dumps(obj.model_dump(mode="json")) # { # 'id': '4f8c1bc4-25fd-40cd-9dbe-2c73639b0dc1', # 'date': '2012-12-12T12:12:12.111111', # 'value': '1.23' # } #pydantic#libs

Резултати

Пронајдени 23 слични објави

Пребарај: #urbanization

当前筛选 #urbanization清除筛选
Interesting Planet 🌍

@interesting_planet_facts · Post #699 · 06.09.2025 г., 16:22

🌎 Land reclamation has transformed Singapore’s size by about 25% since 1819, expanding the island using sand and soil from neighboring countries. The ongoing Tuas Megaport project will create new coastline with over 221 million cubic meters of fill material. ✨ #geography⚡#engineering⚡#urbanization 👉subscribe Interesting Planet ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1397 · 12.05.2026 г., 22:11

🌎 Dubai’s Palm Jumeirah is an artificial archipelago built from over 120 million cubic meters of sand and rock. Constructed in the shape of a palm tree, it adds 56 kilometers of new coastline to the city. ✨ #engineering⚡#urbanization⚡#shoreline 👉subscribe Interesting Planet 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #646 · 24.02.2026 г., 20:31

🌍 The average human today is more likely to live in a city than in the countryside—over 56% of the world’s population is now urban, a dramatic shift from just a few generations ago. ✨ #population⚡#urbanization⚡#cities⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #13 · 09.08.2025 г., 16:27

🌍 Over half of the world’s population now lives in cities, a dramatic shift from 1950 when only about 30% lived in urban areas. Urbanization is rapidly transforming our planet. ✨ #population⚡#urbanization⚡#cities⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍

Amazing Geography 🌍

@amazingeo · Post #15 · 10.08.2025 г., 00:12

🌍 In 1800, fewer than 1 billion people lived on Earth. Today, the world population has soared past 8 billion, with more than half living in urban areas like cities and large towns. ✨ #population⚡#urbanization⚡#demographics⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍

Amazing Geography 🌍

@amazingeo · Post #225 · 12.09.2025 г., 20:12

🌍 In 2022, Nigeria’s largest city, Lagos, became one of only two megacities in Africa to surpass 20 million residents, helping drive Africa’s rapid urban population growth. ✨ #population⚡#urbanization⚡#Africa⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍 ​

Amazing Geography 🌍

@amazingeo · Post #137 · 29.08.2025 г., 09:12

🌍 Some cities, like Johannesburg, are built on high plateaus called "highveld," sitting over 1,700 meters above sea level. Their altitude shapes local climate and city life in unique ways. ✨ #urbanization⚡#elevation⚡#climate⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍 ​

Amazing Geography 🌍

@amazingeo · Post #211 · 10.09.2025 г., 13:12

🌍 By 2050, city dwellers are expected to make up nearly 70% of the global population. Urban areas are now growing twice as fast as rural regions, reshaping how billions of people live. ✨ #urbanization⚡#cities⚡#demographics⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍 ​

Irina Kalabikhina

@kalabikhina · Post #1139 · 26.01.2026 г., 12:11

🆕10(1)/2026 🔗Исторические и современные предикторы региональных культурных различий в индивидуализме и коллективизме в России Андрей А. Григорьев, Альбина А. Галлямова, Дмитрий С. Григорьев, Джон У. Берри В данном исследовании, основанном на экокультурном подходе, изучаются исторические и современные факторы, предсказывающие региональные культурные различия в соотношении индивидуализма (далее – ИНД) и коллективизма (далее – КОЛ, а для соотношения: ИНД/КОЛ) в России, с акцентом на частную собственность на землю в конце XIX – начале XX века и современную занятость в сельском хозяйстве. Анализ показывает, что регионы с более высокой распространенностью частной собственности на землю в 1877 г. и 1905 г. демонстрируют более выраженные тенденции ИНД в современных региональных границах, что свидетельствует о преемственности культурных черт. Кроме того, современные факторы, такие как доля рабочей силы в сельском хозяйстве и этнический состав, в частности доля этнических русских, оказываются значимыми предикторами различий ИНД/КОЛ. Однако урбанизация не обнаруживает значимой связи с региональными культурными различиями в ИНД/КОЛ, что указывает на то, что, хотя она может быть связана с ИНД, она не является основным предиктором. Результаты подчеркивают, что факторы, коренящиеся в традиционных типах хозяйства, вызывают глубокие и долгосрочные последствия для региональных культурных различий, сохраняясь даже в условиях масштабных общественных преобразований, произошедших в советское время. ▫️Публикация в журнале осуществляется бесплатно благодаря поддержке «АКБ «Держава» ПАО» и Экономического факультета МГУ имени М.В.Ломоносова. #population_and_economics#regional_culture#individualism_collectivism#urbanization

Amazing Geography 🌍

@amazingeo · Post #84 · 20.08.2025 г., 16:12

🌍 The largest internal migration in history occurred in China, with over 200 million people moving from rural villages to booming cities since the 1980s, transforming the nation’s economy and society. ✨ #migration⚡#China⚡#urbanization⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍

Amazing Geography 🌍

@amazingeo · Post #83 · 20.08.2025 г., 13:12

🌍 Between 2010 and 2020, India saw more internal migrants than any other country, with tens of millions moving from villages to cities in search of work and better living conditions. ✨ #migration⚡#India⚡#urbanization⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍

Amazing Geography 🌍

@amazingeo · Post #251 · 17.09.2025 г., 03:12

🌍 In 2021, Luxembourg became the first country to offer free nationwide public transport. This move reshapes economic geography by making travel easier and connecting people to jobs and services. ✨ #transport⚡#economy⚡#urbanization⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍 ​

12
ПретходнаСтраница 1 од 2Следна