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

Пребарај: #usiranceasefire

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

@CryptoM · Post #64510 · 09.04.2026 г., 04:38

🚀 Asia's Bond Market Gains Momentum Amid US-Iran Ceasefire Asia's bond market is experiencing renewed momentum as borrowers seize opportunities amid improved risk sentiment following the US-Iran ceasefire. Bloomberg posted on X, highlighting the surge in activity as investors respond to the geopolitical developments. The ceasefire has alleviated some of the uncertainties that previously weighed on the market, encouraging borrowers to take advantage of favorable conditions. This shift in sentiment is reflected in increased issuance and investor interest across the region. Analysts suggest that the current environment may continue to support bond market growth, provided geopolitical tensions remain subdued. The developments underscore the interconnectedness of global events and regional financial markets, with Asia's bond market poised to benefit from the easing of international tensions. #Asia#BondMarket#USIranCeasefire#Investing#Geopolitics#FinancialMarkets#MarketSentiment#InvestorInterest

Crypto M - Crypto News

@CryptoM · Post #64492 · 09.04.2026 г., 03:04

🚀 Mitsui OSK Lines to Review US-Iran Ceasefire Before Navigating Strait of Hormuz Japan’s Mitsui OSK Lines, a leading global shipping company, plans to closely examine the specifics of a ceasefire agreement between the United States and Iran before permitting its vessels to traverse the Strait of Hormuz. Bloomberg posted on X, highlighting the strategic importance of this waterway, which is a critical passage for global oil shipments. The company aims to ensure the safety and security of its operations in the region, given the historical tensions and potential risks associated with navigating this vital maritime route. Mitsui OSK Lines' decision underscores the cautious approach taken by major shipping firms in response to geopolitical developments that could impact international trade and shipping lanes. #MitsuiOSKLines#USIranCeasefire#StraitOfHormuz#globalshipping#internationaltrade#geopolitics#shippingsecurity#oilshipments#maritimeroute#Bloomberg

Crypto M - Crypto News

@CryptoM · Post #64831 · 10.04.2026 г., 02:57

🚀 Economist Predicts Brent-WTI Price Spread to Normalize if US-Iran Ceasefire Holds Economist Hamad Hussain from Capital Economics has stated that the recent ceasefire agreement between the United States and Iran could lead to a normalization of the price spread between Brent and WTI crude oil contracts. According to Jin10, Brent crude typically trades at a premium over WTI crude, but this pattern has been disrupted since the recent conflict began. Hussain noted that the current inverted spread measures the price difference between Brent futures for June delivery and WTI futures for May delivery, with differing contract expiration dates. However, he mentioned that due to significant tightening in the oil market caused by Middle Eastern supply disruptions, and expectations of supply easing in the coming months, the premium of WTI over Brent has widened. #Economist#BrentWTIPriceSpread#USIranCeasefire#CrudeOil#HamadHussain#CapitalEconomics#OilMarket#BrentCrude#WTICrude#MiddleEasternSupply#OilPremium#SupplyDisruptions#OilMarketNormalization