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

Резултати

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

Пребарај: #elephants

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

@interesting_planet_facts · Post #484 · 02.08.2025 г., 03:22

🌎 Deep in the Congo Basin, the African rainforest elephant forges secret trails through dense jungle, creating “elephant highways” that other animals use. These hidden paths help shape entire forest ecosystems by opening routes for seed dispersal and wildlife movement. ✨ #rainforest⚡#elephants⚡#ecosystems 👉subscribe Interesting Planet

Interesting Planet 🌍

@interesting_planet_facts · Post #1312 · 23.02.2026 г., 22:11

🌎 Elephants communicate using deep rumbles that travel through the ground as seismic vibrations. These low-frequency sounds allow herds to “hear” each other from several kilometers away, even when out of sight. ✨ #elephants⚡#communication⚡#animalbehavior 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #783 · 19.09.2025 г., 20:22

🌎 Elephants use infrasound—low-frequency sounds below human hearing—to communicate over distances of several kilometers. These vibrations travel through the ground and air, letting herds coordinate movements and warn of threats. Elephant infrasound calls can be detected up to 10 km away in open savanna. ✨ #elephants⚡#communication⚡#animalintelligence 👉subscribe Interesting Planet ​

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40697 · 24.02.2026 г., 09:20

Elephants can “listen” with their feet. Their foot pads have special nerve receptors that detect ground vibrations, including very low-frequency infrasound. Vibrations from other elephants’ rumbles or footsteps travel through the ground. Signals move through their bodies to the brain. Vibrations can also reach the inner ear through bone conduction. This helps elephants communicate over long distances and sense distant movement. 🐘🌍👣🔊 [Read more] @googlefactss #Elephants#AnimalFacts#Wildlife#Nature#Science#DidYouKnow

💛The Power of a Mother’s Love In Kruger National Park, South Africa, an elephant cow rescued her calf as it was being swept away by a powerful current. 📹 The touching footage comes from an area affected by severe flooding. The natural disaster caused serious damage to the park’s infrastructure: people were evacuated, and some animals had to fend for themselves. According to park officials, most animals moved to higher ground in advance — but not all managed to escape the danger. 🔗Video: https://t.me/aifonline/177687 #SouthAfrica#Wildlife#Nature#Elephants#MothersLove#KrugerNationalPark

🐘🍊Стадо слонов-воришек в провинции Лимпопо, ЮАР, полакомилось апельсинами, которые перевозил сломавшийся в дороге грузовик. _________________________ 🐘🍊 A herd of opportunistic elephants in Limpopo, South Africa, helped themselves to a feast of oranges transported by a truck that had broken on the road. 📹https://www.youtube.com/watch?v=-i5_brrf1cc #ЮАР#Слоны#Природа#Африка#Животные #SouthAfrica#Elephants#Wildlife#Nature#Africa

🇿🇦Tembe Elephant Park🐘 The park was established in the north-eastern part of South Africa in 1983 to protect elephants migrating between South Africa and Mozambique. 🌍 It opened to visitors in 1991 and is now home to about 250 of the largest elephants in the world. 🏞 If you’re into safaris, you can also spot the rest of the Big Five — 🦁 lions, 🐆 leopards, 🦏 rhinos, and 🐃 buffalo. 🎥 Live video: 👉https://www.youtube.com/watch?v=VUJbDTIYlM4 #SouthAfrica#Nature#Safari#BigFive#Elephants#Tembe#Wildlife#Travel#Africa

🐘Слоны — отличные пловцы, и это занятие им очень нравится! Они способны преодолевать расстояния до 50 км. А ещё они умеют нырять — хобот служит им дыхательной трубкой для «подводного плавания». 🤿 #Слоны#Животные#Природа#ЮАР#ИнтересныеФакты ___________________ 🐘Elephants are excellent swimmers — and they love it! They can cover distances of up to 50 km (30 miles). They also dive skillfully, using their trunks as natural snorkels. 🤿 #Elephants#Wildlife#Nature#SouthAfrica#FunFacts 🎥https://t.me/AfroPouchkine/1459