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 слични објави

Пребарај: #daly

当前筛选 #daly清除筛选
Crypto M - Crypto News

@CryptoM · Post #64955 · 10.04.2026 г., 12:09

🚀 Fed's Daly: Ceasefire's Longevity More Crucial Than CPI Data Federal Reserve official Mary Daly emphasized that the primary concern is whether a ceasefire can be sustained. According to Jin10, Daly noted that if the ceasefire holds, the Consumer Price Index (CPI) data becomes less significant. This perspective highlights the importance of geopolitical stability over economic indicators in current assessments. #Fed#Daly#Ceasefire#CPI#GeopoliticalStability#EconomicIndicators

Crypto M - Crypto News

@CryptoM · Post #64954 · 10.04.2026 г., 12:08

🚀 Fed's Daly: Risks to Achieving Full Employment and Inflation Goals Are Balanced The Federal Reserve is currently assessing the risks associated with achieving its dual mandate of full employment and stable inflation. According to Jin10, Mary Daly, President of the Federal Reserve Bank of San Francisco, stated that these risks are essentially balanced. Daly's comments come amid ongoing discussions about the U.S. economic outlook and the Federal Reserve's monetary policy strategy. The central bank continues to monitor economic indicators closely to ensure that its policy measures effectively support the economy's recovery and growth. Daly emphasized the importance of maintaining a balanced approach to address potential challenges in meeting the Fed's objectives. #Fed#Daly#FederalReserve#Inflation#Employment#MonetaryPolicy#EconomicOutlook#USEconomy#DualMandate#InterestRates

Libertà è ragione

@libertaeragione · Post #3982 · 06.10.2023 г., 00:56

#Elezioni#RegnoUnito#Suppletive#RutherglenHamiltonWest Risultati definitivi: Michael #Shanks (#LAB|S&D): 58,6% Katy #Loudon (#SNP|G/EFA): 27,6% Thomas #Kerr (#CON|Centro-destra): 3,9% Gloria #Adebo (#LDEM|RE): 2,9% Cameron #Eadie (#Greens/#ScotsGreens|G/EFA): 2% David #Stark (#Reform|Destra populista): 1,3% Niall #Fraser (#SFP|Destra familiarista cristiana): 1% Bill #Bonnar (#SSP|Sinistra indipendentista): 0,9% Colette #Walker (#ISP|Indipendentisti): 0,7% Christopher #Sermanni (#TUSC|Sinistra): 0,6% Andrew #Daly: 0,3% Ewan #Hoyle (#Volt|G/EFA): 0,2% Prince Ankit #Love, Emperor of India: 0,1% Garry #Cooke: 0% LAB GUADAGNA su SNP. @OsservatorioEsteri