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

Резултати

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

Пребарај: #ants

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

@interesting_planet_facts · Post #754 · 15.09.2025 г., 13:22

🌎 Leafcutter ants and certain fungi share a remarkable partnership. Ants bring leaves underground—not to eat, but to feed a specific fungus they cultivate as food. This mutualism has existed for over 50 million years, making it one of the oldest known examples of symbiosis in the animal world. ✨ #symbiosis⚡#ants⚡#evolution 👉subscribe Interesting Planet ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1386 · 27.04.2026 г., 12:11

🌎 Leafcutter ants farm fungus by cutting leaves and bringing them to underground nests. The ants feed the fungus, then eat the fungus as their main food source. Over 47 species of leafcutter ants are found in Central and South America. ✨ #symbiosis⚡#ants⚡#nature 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1242 · 21.01.2026 г., 12:11

🌎 Army ants in Central and South America show remarkable cooperation by forming living bridges with their bodies. These bridges help the colony cross gaps during raids. Colonies can contain over 200,000 worker ants acting as a single super-organism. ✨ #ants⚡#cooperation⚡#symbiosis 👉subscribe Interesting Planet 👉more Channels ​

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40309 · 12.12.2025 г., 23:01

Ants don't have lungs. They breathe through tiny holes along the sides of their bodies called spiracles. These connect to a network of tubes (tracheae) that deliver oxygen directly to their tissues. [Read more] @googlefactss #Ants#Biology#Entomology#ScienceFacts

Interesting Planet 🌍

@interesting_planet_facts · Post #476 · 31.07.2025 г., 20:22

🌎 The leafcutter ant creates underground gardens by carrying fresh leaves to feed a special fungus, which is their true food. This farming partnership has evolved over millions of years, making these ants nature’s original farmers long before humans. ✨ #ants⚡#fungus⚡#agriculture 👉subscribe Interesting Planet