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

Резултати

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

Пребарај: #datastructures

当前筛选 #datastructures清除筛选
Repositorio data science

@repo_science · Post #3438 · 14.07.2023 г., 19:11

#python#DataStructures#algorithms 🐍 Python Data Structures & Algorithms What you will get in this course: - Data Structures Lists Linked Lists Doubly Linked Lists Stacks & Queues Binary Trees Hash Tables Graphs - Algorithms - Sorting Bubble Sort Selection Sort Insertion Sort Merge Sort Quick Sort - Searching Breadth First Search Depth First Search 🔗Link ----- Main channel:@repo_science Coupons:@freecoupons_reposcience -----

Repositorio data science

@repo_science · Post #3348 · 25.06.2023 г., 17:31

#python#Algorithms#dataStructures 🐍 Hands-On Data Structures and Algorithms with Python: Store, manipulate, and access data effectively and boost the performance of your applications 🖇3rd Edition 📆2022 ✍️Dr. Basant Agarwal 🔗Link ----- Main channel: @repo_science Coupons: @freecoupons_reposcience -----

Repositorio data science

@repo_science · Post #3433 · 12.07.2023 г., 19:56

#DataStructures#Algorithms#Java 🛠 The Ultimate Data Structures & Algorithms Course What You'll Learn... This course is divided into three parts, each about 5 hours long so you can easily complete it. The first part is all about linear data structures and their algorithms: - Big O Notation - Arrays - Linked Lists - Stacks - Queues - Hash Tables The second part covers non-linear data structures and their algorithms: - Binary Trees - AVL Trees - Heaps - Tries - Graphs The third part explores: - Searching Algorithms - Sorting Algorithms - String Manipulation Algorithms 🗣Mosh Hamedani 🔗Link ----- Main channel:@repo_science Coupons:@freecoupons_reposcience -----

Repositorio data science

@repo_science · Post #3109 · 28.04.2023 г., 17:58

#datascientist#datascience#datasciencejobs#dataanalysis#data#dataanalyst#dataanalytics#dataanalystjobs#analytics#python#pythonprogramming#rprogramming#sql#excel#statistics#testing#softwaretesting#projects#projectmanagement#agile#computerscience#programming#webdevelopment#softwaredevelopment#roadmap#visualization#learningeveryday#learning#tutorials#learntocode#apache#powerbi#tableau#machinelearning#ml#ai#artficialintelligence#deeplearning#bigdata#bigdataanalytics#algorithms#mathematics#datastructures#kaggle#nlp#reinforcementlearning#sql#nosql#databases#mongodb ----- Canal principal:@repo_science Cupones: @freecoupons_reposcience -----