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

Резултати

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

Пребарај: #dwarfs

当前筛选 #dwarfs清除筛选
Universe Mysteries 🪐

@cosmomyst · Post #417 · 13.10.2025 г., 15:21

🪐 Deep in the Milky Way, the star J0247-25B is a true cosmic oddball—it’s a rare "pre-helium white dwarf," meaning it’s caught in the act of shedding its outer layers before becoming a typical white dwarf star. This unusual star is much hotter than normal for its size, giving scientists a unique chance to watch stellar evolution unfold before their eyes and providing clues about how stars change shape and temperature toward the end of their lives. ✨ #unusualstars⚡#milkyway⚡#white⚡#dwarfs⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #366 · 03.10.2025 г., 12:21

🪐 One of the most unusual stars known is SDSS J122859.93+104032.9, a "carbon-rich white dwarf" about 1,000 light-years from Earth. Unlike typical white dwarfs—stellar remnants made mostly of hydrogen and helium—this star's atmosphere is packed with carbon, giving it a faint, bluish glow and defying expectations about how dying stars shed their outer layers. ✨ #unusualstars⚡#white⚡#dwarfs⚡#stardust⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #469 · 31.10.2025 г., 12:21

🪐 The star HD 49798, located about 2,000 light-years away in the constellation Puppis, is an unusual subdwarf that forms a pair with a mysterious, ultra-dense white dwarf companion. The white dwarf is spinning at a record-breaking speed of just 13 seconds per rotation, making it one of the fastest-spinning white dwarfs ever found and offering a glimpse into rare, exotic outcomes of stellar evolution. ✨ #unusualstars⚡#white⚡#dwarfs⚡#HD49798⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​