1# Licensed to the Apache Software Foundation (ASF) under one
2# or more contributor license agreements. See the NOTICE file
3# distributed with this work for additional information
4# regarding copyright ownership. The ASF licenses this file
5# to you under the Apache License, Version 2.0 (the
6# "License"); you may not use this file except in compliance
7# with the License. You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing,
12# software distributed under the License is distributed on an
13# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14# KIND, either express or implied. See the License for the
15# specific language governing permissions and limitations
16# under the License.
17from __future__ import annotations
18
19from dataclasses import is_dataclass
20from typing import Any
21
22
23def is_pydantic_model(cls: Any) -> bool:
24 """
25 Return True if the class is a pydantic.main.BaseModel.
26
27 Checking is done by attributes as it is significantly faster than
28 using isinstance.
29 """
30 # __pydantic_fields__ is always present on Pydantic V2 models and is a dict[str, FieldInfo]
31 # __pydantic_validator__ is an internal validator object, always set after model build
32 # Check if it is not a dataclass to prevent detecting pydantic dataclasses as pydantic models
33 return (
34 hasattr(cls, "__pydantic_fields__")
35 and hasattr(cls, "__pydantic_validator__")
36 and not is_dataclass(cls)
37 )