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

Резултати

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

Пребарај: #universe

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

@interesting_planet_facts · Post #1382 · 23.04.2026 г., 22:11

🌎 The coldest known place in the universe is the Boomerang Nebula, located about 5,000 light-years from Earth. Its temperature is just 1 kelvin, or –272°C, which is even colder than the background temperature of space. This nebula formed from rapidly expanding gas blown out by a dying star. ✨ #space⚡#universe⚡#astronomy 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #680 · 03.09.2025 г., 13:22

🌎 The Boötes Void is an enormous empty region of space, spanning about 330 million light-years across. This cosmic void contains far fewer galaxies than expected, making it one of the largest known gaps in the observable universe. ✨ #space⚡#astronomy⚡#universe 👉subscribe Interesting Planet ​

Interesting Planet 🌍

@interesting_planet_facts · Post #626 · 25.08.2025 г., 13:22

🌎 At the edge of the observable universe, mysterious “dark flow” tugs galaxy clusters in the same direction, hinting at unseen forces or realms beyond our cosmic horizon. This puzzling movement can’t be explained by known gravity alone, sparking debate about what lies outside the visible universe. ✨ #space⚡#universe⚡#cosmology 👉subscribe Interesting Planet ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1118 · 10.12.2025 г., 22:11

🌎 Scientists researching the mysteries of parallel worlds often reference "brane theory," which suggests our universe could be a 3D surface, or 'brane,' floating in higher-dimensional space. In this model, multiple branes—each a universe with its own laws—could exist, and gravity may leak between them, which physicists are testing with experiments at facilities like CERN. ✨ #physics⚡#universe⚡#dimensions 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #780 · 19.09.2025 г., 13:22

🌎 Hidden in the vast cosmic darkness, rogue planets drift alone through space without orbiting any star. These “orphan worlds” form when gravitational forces eject young planets from their home systems. Some estimates suggest our galaxy may contain more rogue planets than stars. ✨ #universe⚡#astronomy⚡#exoplanets 👉subscribe Interesting Planet ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1236 · 19.01.2026 г., 12:11

🌎 Mysterious dark matter makes up about 27% of the universe, but it does not emit or absorb light, making it invisible. Scientists detect dark matter only through its gravitational effects on galaxies and galaxy clusters. The leading candidates for dark matter particles are called WIMPs—Weakly Interacting Massive Particles. ✨ #space⚡#universe⚡#astrophysics 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #654 · 30.08.2025 г., 00:22

🌎 An ancient mystery lingers at the center of our galaxy—a supermassive black hole called Sagittarius A*. Its powerful gravity bends space and time, hiding beyond a swirling cloud of stars and gas. This invisible giant shapes the Milky Way, anchoring everything around it with immense, unseen force. ✨ #space⚡#blackhole⚡#universe 👉subscribe Interesting Planet ​

123•••5•••10•••15•••20•••25•••30•••35•••40•••45•••50•••55•••606162
ПретходнаСтраница 1 од 62Следна