Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- infer_4_37_2/lib/python3.10/site-packages/pydantic/__init__.py +428 -0
- infer_4_37_2/lib/python3.10/site-packages/pydantic/annotated_handlers.py +122 -0
- infer_4_37_2/lib/python3.10/site-packages/pydantic/color.py +604 -0
- infer_4_37_2/lib/python3.10/site-packages/pydantic/errors.py +162 -0
- infer_4_37_2/lib/python3.10/site-packages/pydantic/generics.py +5 -0
- infer_4_37_2/lib/python3.10/site-packages/pydantic/mypy.py +1320 -0
- infer_4_37_2/lib/python3.10/site-packages/pydantic/parse.py +5 -0
- infer_4_37_2/lib/python3.10/site-packages/pydantic/validators.py +5 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/__main__.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/_cell_widths.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/_emoji_replace.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/_export_format.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/_fileno.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/_inspect.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/_null_file.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/_spinners.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/_stack.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/_timer.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/_win32_console.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/_windows_renderer.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/_wrap.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/abc.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/ansi.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/bar.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/box.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/cells.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/color.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/color_triplet.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/columns.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/constrain.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/containers.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/emoji.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/file_proxy.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/filesize.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/highlighter.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/json.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/layout.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/markdown.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/measure.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/padding.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/palette.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/progress_bar.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/protocol.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/region.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/repr.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/rule.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/screen.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/segment.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/spinner.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/style.cpython-310.pyc +0 -0
infer_4_37_2/lib/python3.10/site-packages/pydantic/__init__.py
ADDED
|
@@ -0,0 +1,428 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
| 1 |
+
import typing
|
| 2 |
+
from importlib import import_module
|
| 3 |
+
from warnings import warn
|
| 4 |
+
|
| 5 |
+
from ._migration import getattr_migration
|
| 6 |
+
from .version import VERSION
|
| 7 |
+
|
| 8 |
+
if typing.TYPE_CHECKING:
|
| 9 |
+
# import of virtually everything is supported via `__getattr__` below,
|
| 10 |
+
# but we need them here for type checking and IDE support
|
| 11 |
+
import pydantic_core
|
| 12 |
+
from pydantic_core.core_schema import (
|
| 13 |
+
FieldSerializationInfo,
|
| 14 |
+
SerializationInfo,
|
| 15 |
+
SerializerFunctionWrapHandler,
|
| 16 |
+
ValidationInfo,
|
| 17 |
+
ValidatorFunctionWrapHandler,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
from . import dataclasses
|
| 21 |
+
from .aliases import AliasChoices, AliasGenerator, AliasPath
|
| 22 |
+
from .annotated_handlers import GetCoreSchemaHandler, GetJsonSchemaHandler
|
| 23 |
+
from .config import ConfigDict, with_config
|
| 24 |
+
from .errors import *
|
| 25 |
+
from .fields import Field, PrivateAttr, computed_field
|
| 26 |
+
from .functional_serializers import (
|
| 27 |
+
PlainSerializer,
|
| 28 |
+
SerializeAsAny,
|
| 29 |
+
WrapSerializer,
|
| 30 |
+
field_serializer,
|
| 31 |
+
model_serializer,
|
| 32 |
+
)
|
| 33 |
+
from .functional_validators import (
|
| 34 |
+
AfterValidator,
|
| 35 |
+
BeforeValidator,
|
| 36 |
+
InstanceOf,
|
| 37 |
+
PlainValidator,
|
| 38 |
+
SkipValidation,
|
| 39 |
+
WrapValidator,
|
| 40 |
+
field_validator,
|
| 41 |
+
model_validator,
|
| 42 |
+
)
|
| 43 |
+
from .json_schema import WithJsonSchema
|
| 44 |
+
from .main import *
|
| 45 |
+
from .networks import *
|
| 46 |
+
from .type_adapter import TypeAdapter
|
| 47 |
+
from .types import *
|
| 48 |
+
from .validate_call_decorator import validate_call
|
| 49 |
+
from .warnings import (
|
| 50 |
+
PydanticDeprecatedSince20,
|
| 51 |
+
PydanticDeprecatedSince26,
|
| 52 |
+
PydanticDeprecatedSince29,
|
| 53 |
+
PydanticDeprecationWarning,
|
| 54 |
+
PydanticExperimentalWarning,
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
# this encourages pycharm to import `ValidationError` from here, not pydantic_core
|
| 58 |
+
ValidationError = pydantic_core.ValidationError
|
| 59 |
+
from .deprecated.class_validators import root_validator, validator
|
| 60 |
+
from .deprecated.config import BaseConfig, Extra
|
| 61 |
+
from .deprecated.tools import *
|
| 62 |
+
from .root_model import RootModel
|
| 63 |
+
|
| 64 |
+
__version__ = VERSION
|
| 65 |
+
__all__ = (
|
| 66 |
+
# dataclasses
|
| 67 |
+
'dataclasses',
|
| 68 |
+
# functional validators
|
| 69 |
+
'field_validator',
|
| 70 |
+
'model_validator',
|
| 71 |
+
'AfterValidator',
|
| 72 |
+
'BeforeValidator',
|
| 73 |
+
'PlainValidator',
|
| 74 |
+
'WrapValidator',
|
| 75 |
+
'SkipValidation',
|
| 76 |
+
'InstanceOf',
|
| 77 |
+
# JSON Schema
|
| 78 |
+
'WithJsonSchema',
|
| 79 |
+
# deprecated V1 functional validators, these are imported via `__getattr__` below
|
| 80 |
+
'root_validator',
|
| 81 |
+
'validator',
|
| 82 |
+
# functional serializers
|
| 83 |
+
'field_serializer',
|
| 84 |
+
'model_serializer',
|
| 85 |
+
'PlainSerializer',
|
| 86 |
+
'SerializeAsAny',
|
| 87 |
+
'WrapSerializer',
|
| 88 |
+
# config
|
| 89 |
+
'ConfigDict',
|
| 90 |
+
'with_config',
|
| 91 |
+
# deprecated V1 config, these are imported via `__getattr__` below
|
| 92 |
+
'BaseConfig',
|
| 93 |
+
'Extra',
|
| 94 |
+
# validate_call
|
| 95 |
+
'validate_call',
|
| 96 |
+
# errors
|
| 97 |
+
'PydanticErrorCodes',
|
| 98 |
+
'PydanticUserError',
|
| 99 |
+
'PydanticSchemaGenerationError',
|
| 100 |
+
'PydanticImportError',
|
| 101 |
+
'PydanticUndefinedAnnotation',
|
| 102 |
+
'PydanticInvalidForJsonSchema',
|
| 103 |
+
# fields
|
| 104 |
+
'Field',
|
| 105 |
+
'computed_field',
|
| 106 |
+
'PrivateAttr',
|
| 107 |
+
# alias
|
| 108 |
+
'AliasChoices',
|
| 109 |
+
'AliasGenerator',
|
| 110 |
+
'AliasPath',
|
| 111 |
+
# main
|
| 112 |
+
'BaseModel',
|
| 113 |
+
'create_model',
|
| 114 |
+
# network
|
| 115 |
+
'AnyUrl',
|
| 116 |
+
'AnyHttpUrl',
|
| 117 |
+
'FileUrl',
|
| 118 |
+
'HttpUrl',
|
| 119 |
+
'FtpUrl',
|
| 120 |
+
'WebsocketUrl',
|
| 121 |
+
'AnyWebsocketUrl',
|
| 122 |
+
'UrlConstraints',
|
| 123 |
+
'EmailStr',
|
| 124 |
+
'NameEmail',
|
| 125 |
+
'IPvAnyAddress',
|
| 126 |
+
'IPvAnyInterface',
|
| 127 |
+
'IPvAnyNetwork',
|
| 128 |
+
'PostgresDsn',
|
| 129 |
+
'CockroachDsn',
|
| 130 |
+
'AmqpDsn',
|
| 131 |
+
'RedisDsn',
|
| 132 |
+
'MongoDsn',
|
| 133 |
+
'KafkaDsn',
|
| 134 |
+
'NatsDsn',
|
| 135 |
+
'MySQLDsn',
|
| 136 |
+
'MariaDBDsn',
|
| 137 |
+
'ClickHouseDsn',
|
| 138 |
+
'SnowflakeDsn',
|
| 139 |
+
'validate_email',
|
| 140 |
+
# root_model
|
| 141 |
+
'RootModel',
|
| 142 |
+
# deprecated tools, these are imported via `__getattr__` below
|
| 143 |
+
'parse_obj_as',
|
| 144 |
+
'schema_of',
|
| 145 |
+
'schema_json_of',
|
| 146 |
+
# types
|
| 147 |
+
'Strict',
|
| 148 |
+
'StrictStr',
|
| 149 |
+
'conbytes',
|
| 150 |
+
'conlist',
|
| 151 |
+
'conset',
|
| 152 |
+
'confrozenset',
|
| 153 |
+
'constr',
|
| 154 |
+
'StringConstraints',
|
| 155 |
+
'ImportString',
|
| 156 |
+
'conint',
|
| 157 |
+
'PositiveInt',
|
| 158 |
+
'NegativeInt',
|
| 159 |
+
'NonNegativeInt',
|
| 160 |
+
'NonPositiveInt',
|
| 161 |
+
'confloat',
|
| 162 |
+
'PositiveFloat',
|
| 163 |
+
'NegativeFloat',
|
| 164 |
+
'NonNegativeFloat',
|
| 165 |
+
'NonPositiveFloat',
|
| 166 |
+
'FiniteFloat',
|
| 167 |
+
'condecimal',
|
| 168 |
+
'condate',
|
| 169 |
+
'UUID1',
|
| 170 |
+
'UUID3',
|
| 171 |
+
'UUID4',
|
| 172 |
+
'UUID5',
|
| 173 |
+
'FilePath',
|
| 174 |
+
'DirectoryPath',
|
| 175 |
+
'NewPath',
|
| 176 |
+
'Json',
|
| 177 |
+
'Secret',
|
| 178 |
+
'SecretStr',
|
| 179 |
+
'SecretBytes',
|
| 180 |
+
'SocketPath',
|
| 181 |
+
'StrictBool',
|
| 182 |
+
'StrictBytes',
|
| 183 |
+
'StrictInt',
|
| 184 |
+
'StrictFloat',
|
| 185 |
+
'PaymentCardNumber',
|
| 186 |
+
'ByteSize',
|
| 187 |
+
'PastDate',
|
| 188 |
+
'FutureDate',
|
| 189 |
+
'PastDatetime',
|
| 190 |
+
'FutureDatetime',
|
| 191 |
+
'AwareDatetime',
|
| 192 |
+
'NaiveDatetime',
|
| 193 |
+
'AllowInfNan',
|
| 194 |
+
'EncoderProtocol',
|
| 195 |
+
'EncodedBytes',
|
| 196 |
+
'EncodedStr',
|
| 197 |
+
'Base64Encoder',
|
| 198 |
+
'Base64Bytes',
|
| 199 |
+
'Base64Str',
|
| 200 |
+
'Base64UrlBytes',
|
| 201 |
+
'Base64UrlStr',
|
| 202 |
+
'GetPydanticSchema',
|
| 203 |
+
'Tag',
|
| 204 |
+
'Discriminator',
|
| 205 |
+
'JsonValue',
|
| 206 |
+
'FailFast',
|
| 207 |
+
# type_adapter
|
| 208 |
+
'TypeAdapter',
|
| 209 |
+
# version
|
| 210 |
+
'__version__',
|
| 211 |
+
'VERSION',
|
| 212 |
+
# warnings
|
| 213 |
+
'PydanticDeprecatedSince20',
|
| 214 |
+
'PydanticDeprecatedSince26',
|
| 215 |
+
'PydanticDeprecatedSince29',
|
| 216 |
+
'PydanticDeprecationWarning',
|
| 217 |
+
'PydanticExperimentalWarning',
|
| 218 |
+
# annotated handlers
|
| 219 |
+
'GetCoreSchemaHandler',
|
| 220 |
+
'GetJsonSchemaHandler',
|
| 221 |
+
# pydantic_core
|
| 222 |
+
'ValidationError',
|
| 223 |
+
'ValidationInfo',
|
| 224 |
+
'SerializationInfo',
|
| 225 |
+
'ValidatorFunctionWrapHandler',
|
| 226 |
+
'FieldSerializationInfo',
|
| 227 |
+
'SerializerFunctionWrapHandler',
|
| 228 |
+
'OnErrorOmit',
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
# A mapping of {<member name>: (package, <module name>)} defining dynamic imports
|
| 232 |
+
_dynamic_imports: 'dict[str, tuple[str, str]]' = {
|
| 233 |
+
'dataclasses': (__spec__.parent, '__module__'),
|
| 234 |
+
# functional validators
|
| 235 |
+
'field_validator': (__spec__.parent, '.functional_validators'),
|
| 236 |
+
'model_validator': (__spec__.parent, '.functional_validators'),
|
| 237 |
+
'AfterValidator': (__spec__.parent, '.functional_validators'),
|
| 238 |
+
'BeforeValidator': (__spec__.parent, '.functional_validators'),
|
| 239 |
+
'PlainValidator': (__spec__.parent, '.functional_validators'),
|
| 240 |
+
'WrapValidator': (__spec__.parent, '.functional_validators'),
|
| 241 |
+
'SkipValidation': (__spec__.parent, '.functional_validators'),
|
| 242 |
+
'InstanceOf': (__spec__.parent, '.functional_validators'),
|
| 243 |
+
# JSON Schema
|
| 244 |
+
'WithJsonSchema': (__spec__.parent, '.json_schema'),
|
| 245 |
+
# functional serializers
|
| 246 |
+
'field_serializer': (__spec__.parent, '.functional_serializers'),
|
| 247 |
+
'model_serializer': (__spec__.parent, '.functional_serializers'),
|
| 248 |
+
'PlainSerializer': (__spec__.parent, '.functional_serializers'),
|
| 249 |
+
'SerializeAsAny': (__spec__.parent, '.functional_serializers'),
|
| 250 |
+
'WrapSerializer': (__spec__.parent, '.functional_serializers'),
|
| 251 |
+
# config
|
| 252 |
+
'ConfigDict': (__spec__.parent, '.config'),
|
| 253 |
+
'with_config': (__spec__.parent, '.config'),
|
| 254 |
+
# validate call
|
| 255 |
+
'validate_call': (__spec__.parent, '.validate_call_decorator'),
|
| 256 |
+
# errors
|
| 257 |
+
'PydanticErrorCodes': (__spec__.parent, '.errors'),
|
| 258 |
+
'PydanticUserError': (__spec__.parent, '.errors'),
|
| 259 |
+
'PydanticSchemaGenerationError': (__spec__.parent, '.errors'),
|
| 260 |
+
'PydanticImportError': (__spec__.parent, '.errors'),
|
| 261 |
+
'PydanticUndefinedAnnotation': (__spec__.parent, '.errors'),
|
| 262 |
+
'PydanticInvalidForJsonSchema': (__spec__.parent, '.errors'),
|
| 263 |
+
# fields
|
| 264 |
+
'Field': (__spec__.parent, '.fields'),
|
| 265 |
+
'computed_field': (__spec__.parent, '.fields'),
|
| 266 |
+
'PrivateAttr': (__spec__.parent, '.fields'),
|
| 267 |
+
# alias
|
| 268 |
+
'AliasChoices': (__spec__.parent, '.aliases'),
|
| 269 |
+
'AliasGenerator': (__spec__.parent, '.aliases'),
|
| 270 |
+
'AliasPath': (__spec__.parent, '.aliases'),
|
| 271 |
+
# main
|
| 272 |
+
'BaseModel': (__spec__.parent, '.main'),
|
| 273 |
+
'create_model': (__spec__.parent, '.main'),
|
| 274 |
+
# network
|
| 275 |
+
'AnyUrl': (__spec__.parent, '.networks'),
|
| 276 |
+
'AnyHttpUrl': (__spec__.parent, '.networks'),
|
| 277 |
+
'FileUrl': (__spec__.parent, '.networks'),
|
| 278 |
+
'HttpUrl': (__spec__.parent, '.networks'),
|
| 279 |
+
'FtpUrl': (__spec__.parent, '.networks'),
|
| 280 |
+
'WebsocketUrl': (__spec__.parent, '.networks'),
|
| 281 |
+
'AnyWebsocketUrl': (__spec__.parent, '.networks'),
|
| 282 |
+
'UrlConstraints': (__spec__.parent, '.networks'),
|
| 283 |
+
'EmailStr': (__spec__.parent, '.networks'),
|
| 284 |
+
'NameEmail': (__spec__.parent, '.networks'),
|
| 285 |
+
'IPvAnyAddress': (__spec__.parent, '.networks'),
|
| 286 |
+
'IPvAnyInterface': (__spec__.parent, '.networks'),
|
| 287 |
+
'IPvAnyNetwork': (__spec__.parent, '.networks'),
|
| 288 |
+
'PostgresDsn': (__spec__.parent, '.networks'),
|
| 289 |
+
'CockroachDsn': (__spec__.parent, '.networks'),
|
| 290 |
+
'AmqpDsn': (__spec__.parent, '.networks'),
|
| 291 |
+
'RedisDsn': (__spec__.parent, '.networks'),
|
| 292 |
+
'MongoDsn': (__spec__.parent, '.networks'),
|
| 293 |
+
'KafkaDsn': (__spec__.parent, '.networks'),
|
| 294 |
+
'NatsDsn': (__spec__.parent, '.networks'),
|
| 295 |
+
'MySQLDsn': (__spec__.parent, '.networks'),
|
| 296 |
+
'MariaDBDsn': (__spec__.parent, '.networks'),
|
| 297 |
+
'ClickHouseDsn': (__spec__.parent, '.networks'),
|
| 298 |
+
'SnowflakeDsn': (__spec__.parent, '.networks'),
|
| 299 |
+
'validate_email': (__spec__.parent, '.networks'),
|
| 300 |
+
# root_model
|
| 301 |
+
'RootModel': (__spec__.parent, '.root_model'),
|
| 302 |
+
# types
|
| 303 |
+
'Strict': (__spec__.parent, '.types'),
|
| 304 |
+
'StrictStr': (__spec__.parent, '.types'),
|
| 305 |
+
'conbytes': (__spec__.parent, '.types'),
|
| 306 |
+
'conlist': (__spec__.parent, '.types'),
|
| 307 |
+
'conset': (__spec__.parent, '.types'),
|
| 308 |
+
'confrozenset': (__spec__.parent, '.types'),
|
| 309 |
+
'constr': (__spec__.parent, '.types'),
|
| 310 |
+
'StringConstraints': (__spec__.parent, '.types'),
|
| 311 |
+
'ImportString': (__spec__.parent, '.types'),
|
| 312 |
+
'conint': (__spec__.parent, '.types'),
|
| 313 |
+
'PositiveInt': (__spec__.parent, '.types'),
|
| 314 |
+
'NegativeInt': (__spec__.parent, '.types'),
|
| 315 |
+
'NonNegativeInt': (__spec__.parent, '.types'),
|
| 316 |
+
'NonPositiveInt': (__spec__.parent, '.types'),
|
| 317 |
+
'confloat': (__spec__.parent, '.types'),
|
| 318 |
+
'PositiveFloat': (__spec__.parent, '.types'),
|
| 319 |
+
'NegativeFloat': (__spec__.parent, '.types'),
|
| 320 |
+
'NonNegativeFloat': (__spec__.parent, '.types'),
|
| 321 |
+
'NonPositiveFloat': (__spec__.parent, '.types'),
|
| 322 |
+
'FiniteFloat': (__spec__.parent, '.types'),
|
| 323 |
+
'condecimal': (__spec__.parent, '.types'),
|
| 324 |
+
'condate': (__spec__.parent, '.types'),
|
| 325 |
+
'UUID1': (__spec__.parent, '.types'),
|
| 326 |
+
'UUID3': (__spec__.parent, '.types'),
|
| 327 |
+
'UUID4': (__spec__.parent, '.types'),
|
| 328 |
+
'UUID5': (__spec__.parent, '.types'),
|
| 329 |
+
'FilePath': (__spec__.parent, '.types'),
|
| 330 |
+
'DirectoryPath': (__spec__.parent, '.types'),
|
| 331 |
+
'NewPath': (__spec__.parent, '.types'),
|
| 332 |
+
'Json': (__spec__.parent, '.types'),
|
| 333 |
+
'Secret': (__spec__.parent, '.types'),
|
| 334 |
+
'SecretStr': (__spec__.parent, '.types'),
|
| 335 |
+
'SecretBytes': (__spec__.parent, '.types'),
|
| 336 |
+
'StrictBool': (__spec__.parent, '.types'),
|
| 337 |
+
'StrictBytes': (__spec__.parent, '.types'),
|
| 338 |
+
'StrictInt': (__spec__.parent, '.types'),
|
| 339 |
+
'StrictFloat': (__spec__.parent, '.types'),
|
| 340 |
+
'PaymentCardNumber': (__spec__.parent, '.types'),
|
| 341 |
+
'ByteSize': (__spec__.parent, '.types'),
|
| 342 |
+
'PastDate': (__spec__.parent, '.types'),
|
| 343 |
+
'SocketPath': (__spec__.parent, '.types'),
|
| 344 |
+
'FutureDate': (__spec__.parent, '.types'),
|
| 345 |
+
'PastDatetime': (__spec__.parent, '.types'),
|
| 346 |
+
'FutureDatetime': (__spec__.parent, '.types'),
|
| 347 |
+
'AwareDatetime': (__spec__.parent, '.types'),
|
| 348 |
+
'NaiveDatetime': (__spec__.parent, '.types'),
|
| 349 |
+
'AllowInfNan': (__spec__.parent, '.types'),
|
| 350 |
+
'EncoderProtocol': (__spec__.parent, '.types'),
|
| 351 |
+
'EncodedBytes': (__spec__.parent, '.types'),
|
| 352 |
+
'EncodedStr': (__spec__.parent, '.types'),
|
| 353 |
+
'Base64Encoder': (__spec__.parent, '.types'),
|
| 354 |
+
'Base64Bytes': (__spec__.parent, '.types'),
|
| 355 |
+
'Base64Str': (__spec__.parent, '.types'),
|
| 356 |
+
'Base64UrlBytes': (__spec__.parent, '.types'),
|
| 357 |
+
'Base64UrlStr': (__spec__.parent, '.types'),
|
| 358 |
+
'GetPydanticSchema': (__spec__.parent, '.types'),
|
| 359 |
+
'Tag': (__spec__.parent, '.types'),
|
| 360 |
+
'Discriminator': (__spec__.parent, '.types'),
|
| 361 |
+
'JsonValue': (__spec__.parent, '.types'),
|
| 362 |
+
'OnErrorOmit': (__spec__.parent, '.types'),
|
| 363 |
+
'FailFast': (__spec__.parent, '.types'),
|
| 364 |
+
# type_adapter
|
| 365 |
+
'TypeAdapter': (__spec__.parent, '.type_adapter'),
|
| 366 |
+
# warnings
|
| 367 |
+
'PydanticDeprecatedSince20': (__spec__.parent, '.warnings'),
|
| 368 |
+
'PydanticDeprecatedSince26': (__spec__.parent, '.warnings'),
|
| 369 |
+
'PydanticDeprecatedSince29': (__spec__.parent, '.warnings'),
|
| 370 |
+
'PydanticDeprecationWarning': (__spec__.parent, '.warnings'),
|
| 371 |
+
'PydanticExperimentalWarning': (__spec__.parent, '.warnings'),
|
| 372 |
+
# annotated handlers
|
| 373 |
+
'GetCoreSchemaHandler': (__spec__.parent, '.annotated_handlers'),
|
| 374 |
+
'GetJsonSchemaHandler': (__spec__.parent, '.annotated_handlers'),
|
| 375 |
+
# pydantic_core stuff
|
| 376 |
+
'ValidationError': ('pydantic_core', '.'),
|
| 377 |
+
'ValidationInfo': ('pydantic_core', '.core_schema'),
|
| 378 |
+
'SerializationInfo': ('pydantic_core', '.core_schema'),
|
| 379 |
+
'ValidatorFunctionWrapHandler': ('pydantic_core', '.core_schema'),
|
| 380 |
+
'FieldSerializationInfo': ('pydantic_core', '.core_schema'),
|
| 381 |
+
'SerializerFunctionWrapHandler': ('pydantic_core', '.core_schema'),
|
| 382 |
+
# deprecated, mostly not included in __all__
|
| 383 |
+
'root_validator': (__spec__.parent, '.deprecated.class_validators'),
|
| 384 |
+
'validator': (__spec__.parent, '.deprecated.class_validators'),
|
| 385 |
+
'BaseConfig': (__spec__.parent, '.deprecated.config'),
|
| 386 |
+
'Extra': (__spec__.parent, '.deprecated.config'),
|
| 387 |
+
'parse_obj_as': (__spec__.parent, '.deprecated.tools'),
|
| 388 |
+
'schema_of': (__spec__.parent, '.deprecated.tools'),
|
| 389 |
+
'schema_json_of': (__spec__.parent, '.deprecated.tools'),
|
| 390 |
+
# deprecated dynamic imports
|
| 391 |
+
'FieldValidationInfo': ('pydantic_core', '.core_schema'),
|
| 392 |
+
'GenerateSchema': (__spec__.parent, '._internal._generate_schema'),
|
| 393 |
+
}
|
| 394 |
+
_deprecated_dynamic_imports = {'FieldValidationInfo', 'GenerateSchema'}
|
| 395 |
+
|
| 396 |
+
_getattr_migration = getattr_migration(__name__)
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def __getattr__(attr_name: str) -> object:
|
| 400 |
+
if attr_name in _deprecated_dynamic_imports:
|
| 401 |
+
warn(
|
| 402 |
+
f'Importing {attr_name} from `pydantic` is deprecated. This feature is either no longer supported, or is not public.',
|
| 403 |
+
DeprecationWarning,
|
| 404 |
+
stacklevel=2,
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
dynamic_attr = _dynamic_imports.get(attr_name)
|
| 408 |
+
if dynamic_attr is None:
|
| 409 |
+
return _getattr_migration(attr_name)
|
| 410 |
+
|
| 411 |
+
package, module_name = dynamic_attr
|
| 412 |
+
|
| 413 |
+
if module_name == '__module__':
|
| 414 |
+
result = import_module(f'.{attr_name}', package=package)
|
| 415 |
+
globals()[attr_name] = result
|
| 416 |
+
return result
|
| 417 |
+
else:
|
| 418 |
+
module = import_module(module_name, package=package)
|
| 419 |
+
result = getattr(module, attr_name)
|
| 420 |
+
g = globals()
|
| 421 |
+
for k, (_, v_module_name) in _dynamic_imports.items():
|
| 422 |
+
if v_module_name == module_name and k not in _deprecated_dynamic_imports:
|
| 423 |
+
g[k] = getattr(module, k)
|
| 424 |
+
return result
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def __dir__() -> 'list[str]':
|
| 428 |
+
return list(__all__)
|
infer_4_37_2/lib/python3.10/site-packages/pydantic/annotated_handlers.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Type annotations to use with `__get_pydantic_core_schema__` and `__get_pydantic_json_schema__`."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations as _annotations
|
| 4 |
+
|
| 5 |
+
from typing import TYPE_CHECKING, Any, Union
|
| 6 |
+
|
| 7 |
+
from pydantic_core import core_schema
|
| 8 |
+
|
| 9 |
+
if TYPE_CHECKING:
|
| 10 |
+
from ._internal._namespace_utils import NamespacesTuple
|
| 11 |
+
from .json_schema import JsonSchemaMode, JsonSchemaValue
|
| 12 |
+
|
| 13 |
+
CoreSchemaOrField = Union[
|
| 14 |
+
core_schema.CoreSchema,
|
| 15 |
+
core_schema.ModelField,
|
| 16 |
+
core_schema.DataclassField,
|
| 17 |
+
core_schema.TypedDictField,
|
| 18 |
+
core_schema.ComputedField,
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
__all__ = 'GetJsonSchemaHandler', 'GetCoreSchemaHandler'
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class GetJsonSchemaHandler:
|
| 25 |
+
"""Handler to call into the next JSON schema generation function.
|
| 26 |
+
|
| 27 |
+
Attributes:
|
| 28 |
+
mode: Json schema mode, can be `validation` or `serialization`.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
mode: JsonSchemaMode
|
| 32 |
+
|
| 33 |
+
def __call__(self, core_schema: CoreSchemaOrField, /) -> JsonSchemaValue:
|
| 34 |
+
"""Call the inner handler and get the JsonSchemaValue it returns.
|
| 35 |
+
This will call the next JSON schema modifying function up until it calls
|
| 36 |
+
into `pydantic.json_schema.GenerateJsonSchema`, which will raise a
|
| 37 |
+
`pydantic.errors.PydanticInvalidForJsonSchema` error if it cannot generate
|
| 38 |
+
a JSON schema.
|
| 39 |
+
|
| 40 |
+
Args:
|
| 41 |
+
core_schema: A `pydantic_core.core_schema.CoreSchema`.
|
| 42 |
+
|
| 43 |
+
Returns:
|
| 44 |
+
JsonSchemaValue: The JSON schema generated by the inner JSON schema modify
|
| 45 |
+
functions.
|
| 46 |
+
"""
|
| 47 |
+
raise NotImplementedError
|
| 48 |
+
|
| 49 |
+
def resolve_ref_schema(self, maybe_ref_json_schema: JsonSchemaValue, /) -> JsonSchemaValue:
|
| 50 |
+
"""Get the real schema for a `{"$ref": ...}` schema.
|
| 51 |
+
If the schema given is not a `$ref` schema, it will be returned as is.
|
| 52 |
+
This means you don't have to check before calling this function.
|
| 53 |
+
|
| 54 |
+
Args:
|
| 55 |
+
maybe_ref_json_schema: A JsonSchemaValue which may be a `$ref` schema.
|
| 56 |
+
|
| 57 |
+
Raises:
|
| 58 |
+
LookupError: If the ref is not found.
|
| 59 |
+
|
| 60 |
+
Returns:
|
| 61 |
+
JsonSchemaValue: A JsonSchemaValue that has no `$ref`.
|
| 62 |
+
"""
|
| 63 |
+
raise NotImplementedError
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class GetCoreSchemaHandler:
|
| 67 |
+
"""Handler to call into the next CoreSchema schema generation function."""
|
| 68 |
+
|
| 69 |
+
def __call__(self, source_type: Any, /) -> core_schema.CoreSchema:
|
| 70 |
+
"""Call the inner handler and get the CoreSchema it returns.
|
| 71 |
+
This will call the next CoreSchema modifying function up until it calls
|
| 72 |
+
into Pydantic's internal schema generation machinery, which will raise a
|
| 73 |
+
`pydantic.errors.PydanticSchemaGenerationError` error if it cannot generate
|
| 74 |
+
a CoreSchema for the given source type.
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
source_type: The input type.
|
| 78 |
+
|
| 79 |
+
Returns:
|
| 80 |
+
CoreSchema: The `pydantic-core` CoreSchema generated.
|
| 81 |
+
"""
|
| 82 |
+
raise NotImplementedError
|
| 83 |
+
|
| 84 |
+
def generate_schema(self, source_type: Any, /) -> core_schema.CoreSchema:
|
| 85 |
+
"""Generate a schema unrelated to the current context.
|
| 86 |
+
Use this function if e.g. you are handling schema generation for a sequence
|
| 87 |
+
and want to generate a schema for its items.
|
| 88 |
+
Otherwise, you may end up doing something like applying a `min_length` constraint
|
| 89 |
+
that was intended for the sequence itself to its items!
|
| 90 |
+
|
| 91 |
+
Args:
|
| 92 |
+
source_type: The input type.
|
| 93 |
+
|
| 94 |
+
Returns:
|
| 95 |
+
CoreSchema: The `pydantic-core` CoreSchema generated.
|
| 96 |
+
"""
|
| 97 |
+
raise NotImplementedError
|
| 98 |
+
|
| 99 |
+
def resolve_ref_schema(self, maybe_ref_schema: core_schema.CoreSchema, /) -> core_schema.CoreSchema:
|
| 100 |
+
"""Get the real schema for a `definition-ref` schema.
|
| 101 |
+
If the schema given is not a `definition-ref` schema, it will be returned as is.
|
| 102 |
+
This means you don't have to check before calling this function.
|
| 103 |
+
|
| 104 |
+
Args:
|
| 105 |
+
maybe_ref_schema: A `CoreSchema`, `ref`-based or not.
|
| 106 |
+
|
| 107 |
+
Raises:
|
| 108 |
+
LookupError: If the `ref` is not found.
|
| 109 |
+
|
| 110 |
+
Returns:
|
| 111 |
+
A concrete `CoreSchema`.
|
| 112 |
+
"""
|
| 113 |
+
raise NotImplementedError
|
| 114 |
+
|
| 115 |
+
@property
|
| 116 |
+
def field_name(self) -> str | None:
|
| 117 |
+
"""Get the name of the closest field to this validator."""
|
| 118 |
+
raise NotImplementedError
|
| 119 |
+
|
| 120 |
+
def _get_types_namespace(self) -> NamespacesTuple:
|
| 121 |
+
"""Internal method used during type resolution for serializer annotations."""
|
| 122 |
+
raise NotImplementedError
|
infer_4_37_2/lib/python3.10/site-packages/pydantic/color.py
ADDED
|
@@ -0,0 +1,604 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Color definitions are used as per the CSS3
|
| 2 |
+
[CSS Color Module Level 3](http://www.w3.org/TR/css3-color/#svg-color) specification.
|
| 3 |
+
|
| 4 |
+
A few colors have multiple names referring to the sames colors, eg. `grey` and `gray` or `aqua` and `cyan`.
|
| 5 |
+
|
| 6 |
+
In these cases the _last_ color when sorted alphabetically takes preferences,
|
| 7 |
+
eg. `Color((0, 255, 255)).as_named() == 'cyan'` because "cyan" comes after "aqua".
|
| 8 |
+
|
| 9 |
+
Warning: Deprecated
|
| 10 |
+
The `Color` class is deprecated, use `pydantic_extra_types` instead.
|
| 11 |
+
See [`pydantic-extra-types.Color`](../usage/types/extra_types/color_types.md)
|
| 12 |
+
for more information.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import math
|
| 16 |
+
import re
|
| 17 |
+
from colorsys import hls_to_rgb, rgb_to_hls
|
| 18 |
+
from typing import Any, Callable, Optional, Tuple, Type, Union, cast
|
| 19 |
+
|
| 20 |
+
from pydantic_core import CoreSchema, PydanticCustomError, core_schema
|
| 21 |
+
from typing_extensions import deprecated
|
| 22 |
+
|
| 23 |
+
from ._internal import _repr
|
| 24 |
+
from ._internal._schema_generation_shared import GetJsonSchemaHandler as _GetJsonSchemaHandler
|
| 25 |
+
from .json_schema import JsonSchemaValue
|
| 26 |
+
from .warnings import PydanticDeprecatedSince20
|
| 27 |
+
|
| 28 |
+
ColorTuple = Union[Tuple[int, int, int], Tuple[int, int, int, float]]
|
| 29 |
+
ColorType = Union[ColorTuple, str]
|
| 30 |
+
HslColorTuple = Union[Tuple[float, float, float], Tuple[float, float, float, float]]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class RGBA:
|
| 34 |
+
"""Internal use only as a representation of a color."""
|
| 35 |
+
|
| 36 |
+
__slots__ = 'r', 'g', 'b', 'alpha', '_tuple'
|
| 37 |
+
|
| 38 |
+
def __init__(self, r: float, g: float, b: float, alpha: Optional[float]):
|
| 39 |
+
self.r = r
|
| 40 |
+
self.g = g
|
| 41 |
+
self.b = b
|
| 42 |
+
self.alpha = alpha
|
| 43 |
+
|
| 44 |
+
self._tuple: Tuple[float, float, float, Optional[float]] = (r, g, b, alpha)
|
| 45 |
+
|
| 46 |
+
def __getitem__(self, item: Any) -> Any:
|
| 47 |
+
return self._tuple[item]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# these are not compiled here to avoid import slowdown, they'll be compiled the first time they're used, then cached
|
| 51 |
+
_r_255 = r'(\d{1,3}(?:\.\d+)?)'
|
| 52 |
+
_r_comma = r'\s*,\s*'
|
| 53 |
+
_r_alpha = r'(\d(?:\.\d+)?|\.\d+|\d{1,2}%)'
|
| 54 |
+
_r_h = r'(-?\d+(?:\.\d+)?|-?\.\d+)(deg|rad|turn)?'
|
| 55 |
+
_r_sl = r'(\d{1,3}(?:\.\d+)?)%'
|
| 56 |
+
r_hex_short = r'\s*(?:#|0x)?([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])?\s*'
|
| 57 |
+
r_hex_long = r'\s*(?:#|0x)?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?\s*'
|
| 58 |
+
# CSS3 RGB examples: rgb(0, 0, 0), rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 50%)
|
| 59 |
+
r_rgb = rf'\s*rgba?\(\s*{_r_255}{_r_comma}{_r_255}{_r_comma}{_r_255}(?:{_r_comma}{_r_alpha})?\s*\)\s*'
|
| 60 |
+
# CSS3 HSL examples: hsl(270, 60%, 50%), hsla(270, 60%, 50%, 0.5), hsla(270, 60%, 50%, 50%)
|
| 61 |
+
r_hsl = rf'\s*hsla?\(\s*{_r_h}{_r_comma}{_r_sl}{_r_comma}{_r_sl}(?:{_r_comma}{_r_alpha})?\s*\)\s*'
|
| 62 |
+
# CSS4 RGB examples: rgb(0 0 0), rgb(0 0 0 / 0.5), rgb(0 0 0 / 50%), rgba(0 0 0 / 50%)
|
| 63 |
+
r_rgb_v4_style = rf'\s*rgba?\(\s*{_r_255}\s+{_r_255}\s+{_r_255}(?:\s*/\s*{_r_alpha})?\s*\)\s*'
|
| 64 |
+
# CSS4 HSL examples: hsl(270 60% 50%), hsl(270 60% 50% / 0.5), hsl(270 60% 50% / 50%), hsla(270 60% 50% / 50%)
|
| 65 |
+
r_hsl_v4_style = rf'\s*hsla?\(\s*{_r_h}\s+{_r_sl}\s+{_r_sl}(?:\s*/\s*{_r_alpha})?\s*\)\s*'
|
| 66 |
+
|
| 67 |
+
# colors where the two hex characters are the same, if all colors match this the short version of hex colors can be used
|
| 68 |
+
repeat_colors = {int(c * 2, 16) for c in '0123456789abcdef'}
|
| 69 |
+
rads = 2 * math.pi
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@deprecated(
|
| 73 |
+
'The `Color` class is deprecated, use `pydantic_extra_types` instead. '
|
| 74 |
+
'See https://docs.pydantic.dev/latest/api/pydantic_extra_types_color/.',
|
| 75 |
+
category=PydanticDeprecatedSince20,
|
| 76 |
+
)
|
| 77 |
+
class Color(_repr.Representation):
|
| 78 |
+
"""Represents a color."""
|
| 79 |
+
|
| 80 |
+
__slots__ = '_original', '_rgba'
|
| 81 |
+
|
| 82 |
+
def __init__(self, value: ColorType) -> None:
|
| 83 |
+
self._rgba: RGBA
|
| 84 |
+
self._original: ColorType
|
| 85 |
+
if isinstance(value, (tuple, list)):
|
| 86 |
+
self._rgba = parse_tuple(value)
|
| 87 |
+
elif isinstance(value, str):
|
| 88 |
+
self._rgba = parse_str(value)
|
| 89 |
+
elif isinstance(value, Color):
|
| 90 |
+
self._rgba = value._rgba
|
| 91 |
+
value = value._original
|
| 92 |
+
else:
|
| 93 |
+
raise PydanticCustomError(
|
| 94 |
+
'color_error', 'value is not a valid color: value must be a tuple, list or string'
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
# if we've got here value must be a valid color
|
| 98 |
+
self._original = value
|
| 99 |
+
|
| 100 |
+
@classmethod
|
| 101 |
+
def __get_pydantic_json_schema__(
|
| 102 |
+
cls, core_schema: core_schema.CoreSchema, handler: _GetJsonSchemaHandler
|
| 103 |
+
) -> JsonSchemaValue:
|
| 104 |
+
field_schema = {}
|
| 105 |
+
field_schema.update(type='string', format='color')
|
| 106 |
+
return field_schema
|
| 107 |
+
|
| 108 |
+
def original(self) -> ColorType:
|
| 109 |
+
"""Original value passed to `Color`."""
|
| 110 |
+
return self._original
|
| 111 |
+
|
| 112 |
+
def as_named(self, *, fallback: bool = False) -> str:
|
| 113 |
+
"""Returns the name of the color if it can be found in `COLORS_BY_VALUE` dictionary,
|
| 114 |
+
otherwise returns the hexadecimal representation of the color or raises `ValueError`.
|
| 115 |
+
|
| 116 |
+
Args:
|
| 117 |
+
fallback: If True, falls back to returning the hexadecimal representation of
|
| 118 |
+
the color instead of raising a ValueError when no named color is found.
|
| 119 |
+
|
| 120 |
+
Returns:
|
| 121 |
+
The name of the color, or the hexadecimal representation of the color.
|
| 122 |
+
|
| 123 |
+
Raises:
|
| 124 |
+
ValueError: When no named color is found and fallback is `False`.
|
| 125 |
+
"""
|
| 126 |
+
if self._rgba.alpha is None:
|
| 127 |
+
rgb = cast(Tuple[int, int, int], self.as_rgb_tuple())
|
| 128 |
+
try:
|
| 129 |
+
return COLORS_BY_VALUE[rgb]
|
| 130 |
+
except KeyError as e:
|
| 131 |
+
if fallback:
|
| 132 |
+
return self.as_hex()
|
| 133 |
+
else:
|
| 134 |
+
raise ValueError('no named color found, use fallback=True, as_hex() or as_rgb()') from e
|
| 135 |
+
else:
|
| 136 |
+
return self.as_hex()
|
| 137 |
+
|
| 138 |
+
def as_hex(self) -> str:
|
| 139 |
+
"""Returns the hexadecimal representation of the color.
|
| 140 |
+
|
| 141 |
+
Hex string representing the color can be 3, 4, 6, or 8 characters depending on whether the string
|
| 142 |
+
a "short" representation of the color is possible and whether there's an alpha channel.
|
| 143 |
+
|
| 144 |
+
Returns:
|
| 145 |
+
The hexadecimal representation of the color.
|
| 146 |
+
"""
|
| 147 |
+
values = [float_to_255(c) for c in self._rgba[:3]]
|
| 148 |
+
if self._rgba.alpha is not None:
|
| 149 |
+
values.append(float_to_255(self._rgba.alpha))
|
| 150 |
+
|
| 151 |
+
as_hex = ''.join(f'{v:02x}' for v in values)
|
| 152 |
+
if all(c in repeat_colors for c in values):
|
| 153 |
+
as_hex = ''.join(as_hex[c] for c in range(0, len(as_hex), 2))
|
| 154 |
+
return '#' + as_hex
|
| 155 |
+
|
| 156 |
+
def as_rgb(self) -> str:
|
| 157 |
+
"""Color as an `rgb(<r>, <g>, <b>)` or `rgba(<r>, <g>, <b>, <a>)` string."""
|
| 158 |
+
if self._rgba.alpha is None:
|
| 159 |
+
return f'rgb({float_to_255(self._rgba.r)}, {float_to_255(self._rgba.g)}, {float_to_255(self._rgba.b)})'
|
| 160 |
+
else:
|
| 161 |
+
return (
|
| 162 |
+
f'rgba({float_to_255(self._rgba.r)}, {float_to_255(self._rgba.g)}, {float_to_255(self._rgba.b)}, '
|
| 163 |
+
f'{round(self._alpha_float(), 2)})'
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
def as_rgb_tuple(self, *, alpha: Optional[bool] = None) -> ColorTuple:
|
| 167 |
+
"""Returns the color as an RGB or RGBA tuple.
|
| 168 |
+
|
| 169 |
+
Args:
|
| 170 |
+
alpha: Whether to include the alpha channel. There are three options for this input:
|
| 171 |
+
|
| 172 |
+
- `None` (default): Include alpha only if it's set. (e.g. not `None`)
|
| 173 |
+
- `True`: Always include alpha.
|
| 174 |
+
- `False`: Always omit alpha.
|
| 175 |
+
|
| 176 |
+
Returns:
|
| 177 |
+
A tuple that contains the values of the red, green, and blue channels in the range 0 to 255.
|
| 178 |
+
If alpha is included, it is in the range 0 to 1.
|
| 179 |
+
"""
|
| 180 |
+
r, g, b = (float_to_255(c) for c in self._rgba[:3])
|
| 181 |
+
if alpha is None:
|
| 182 |
+
if self._rgba.alpha is None:
|
| 183 |
+
return r, g, b
|
| 184 |
+
else:
|
| 185 |
+
return r, g, b, self._alpha_float()
|
| 186 |
+
elif alpha:
|
| 187 |
+
return r, g, b, self._alpha_float()
|
| 188 |
+
else:
|
| 189 |
+
# alpha is False
|
| 190 |
+
return r, g, b
|
| 191 |
+
|
| 192 |
+
def as_hsl(self) -> str:
|
| 193 |
+
"""Color as an `hsl(<h>, <s>, <l>)` or `hsl(<h>, <s>, <l>, <a>)` string."""
|
| 194 |
+
if self._rgba.alpha is None:
|
| 195 |
+
h, s, li = self.as_hsl_tuple(alpha=False) # type: ignore
|
| 196 |
+
return f'hsl({h * 360:0.0f}, {s:0.0%}, {li:0.0%})'
|
| 197 |
+
else:
|
| 198 |
+
h, s, li, a = self.as_hsl_tuple(alpha=True) # type: ignore
|
| 199 |
+
return f'hsl({h * 360:0.0f}, {s:0.0%}, {li:0.0%}, {round(a, 2)})'
|
| 200 |
+
|
| 201 |
+
def as_hsl_tuple(self, *, alpha: Optional[bool] = None) -> HslColorTuple:
|
| 202 |
+
"""Returns the color as an HSL or HSLA tuple.
|
| 203 |
+
|
| 204 |
+
Args:
|
| 205 |
+
alpha: Whether to include the alpha channel.
|
| 206 |
+
|
| 207 |
+
- `None` (default): Include the alpha channel only if it's set (e.g. not `None`).
|
| 208 |
+
- `True`: Always include alpha.
|
| 209 |
+
- `False`: Always omit alpha.
|
| 210 |
+
|
| 211 |
+
Returns:
|
| 212 |
+
The color as a tuple of hue, saturation, lightness, and alpha (if included).
|
| 213 |
+
All elements are in the range 0 to 1.
|
| 214 |
+
|
| 215 |
+
Note:
|
| 216 |
+
This is HSL as used in HTML and most other places, not HLS as used in Python's `colorsys`.
|
| 217 |
+
"""
|
| 218 |
+
h, l, s = rgb_to_hls(self._rgba.r, self._rgba.g, self._rgba.b) # noqa: E741
|
| 219 |
+
if alpha is None:
|
| 220 |
+
if self._rgba.alpha is None:
|
| 221 |
+
return h, s, l
|
| 222 |
+
else:
|
| 223 |
+
return h, s, l, self._alpha_float()
|
| 224 |
+
if alpha:
|
| 225 |
+
return h, s, l, self._alpha_float()
|
| 226 |
+
else:
|
| 227 |
+
# alpha is False
|
| 228 |
+
return h, s, l
|
| 229 |
+
|
| 230 |
+
def _alpha_float(self) -> float:
|
| 231 |
+
return 1 if self._rgba.alpha is None else self._rgba.alpha
|
| 232 |
+
|
| 233 |
+
@classmethod
|
| 234 |
+
def __get_pydantic_core_schema__(
|
| 235 |
+
cls, source: Type[Any], handler: Callable[[Any], CoreSchema]
|
| 236 |
+
) -> core_schema.CoreSchema:
|
| 237 |
+
return core_schema.with_info_plain_validator_function(
|
| 238 |
+
cls._validate, serialization=core_schema.to_string_ser_schema()
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
@classmethod
|
| 242 |
+
def _validate(cls, __input_value: Any, _: Any) -> 'Color':
|
| 243 |
+
return cls(__input_value)
|
| 244 |
+
|
| 245 |
+
def __str__(self) -> str:
|
| 246 |
+
return self.as_named(fallback=True)
|
| 247 |
+
|
| 248 |
+
def __repr_args__(self) -> '_repr.ReprArgs':
|
| 249 |
+
return [(None, self.as_named(fallback=True))] + [('rgb', self.as_rgb_tuple())]
|
| 250 |
+
|
| 251 |
+
def __eq__(self, other: Any) -> bool:
|
| 252 |
+
return isinstance(other, Color) and self.as_rgb_tuple() == other.as_rgb_tuple()
|
| 253 |
+
|
| 254 |
+
def __hash__(self) -> int:
|
| 255 |
+
return hash(self.as_rgb_tuple())
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def parse_tuple(value: Tuple[Any, ...]) -> RGBA:
|
| 259 |
+
"""Parse a tuple or list to get RGBA values.
|
| 260 |
+
|
| 261 |
+
Args:
|
| 262 |
+
value: A tuple or list.
|
| 263 |
+
|
| 264 |
+
Returns:
|
| 265 |
+
An `RGBA` tuple parsed from the input tuple.
|
| 266 |
+
|
| 267 |
+
Raises:
|
| 268 |
+
PydanticCustomError: If tuple is not valid.
|
| 269 |
+
"""
|
| 270 |
+
if len(value) == 3:
|
| 271 |
+
r, g, b = (parse_color_value(v) for v in value)
|
| 272 |
+
return RGBA(r, g, b, None)
|
| 273 |
+
elif len(value) == 4:
|
| 274 |
+
r, g, b = (parse_color_value(v) for v in value[:3])
|
| 275 |
+
return RGBA(r, g, b, parse_float_alpha(value[3]))
|
| 276 |
+
else:
|
| 277 |
+
raise PydanticCustomError('color_error', 'value is not a valid color: tuples must have length 3 or 4')
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def parse_str(value: str) -> RGBA:
|
| 281 |
+
"""Parse a string representing a color to an RGBA tuple.
|
| 282 |
+
|
| 283 |
+
Possible formats for the input string include:
|
| 284 |
+
|
| 285 |
+
* named color, see `COLORS_BY_NAME`
|
| 286 |
+
* hex short eg. `<prefix>fff` (prefix can be `#`, `0x` or nothing)
|
| 287 |
+
* hex long eg. `<prefix>ffffff` (prefix can be `#`, `0x` or nothing)
|
| 288 |
+
* `rgb(<r>, <g>, <b>)`
|
| 289 |
+
* `rgba(<r>, <g>, <b>, <a>)`
|
| 290 |
+
|
| 291 |
+
Args:
|
| 292 |
+
value: A string representing a color.
|
| 293 |
+
|
| 294 |
+
Returns:
|
| 295 |
+
An `RGBA` tuple parsed from the input string.
|
| 296 |
+
|
| 297 |
+
Raises:
|
| 298 |
+
ValueError: If the input string cannot be parsed to an RGBA tuple.
|
| 299 |
+
"""
|
| 300 |
+
value_lower = value.lower()
|
| 301 |
+
try:
|
| 302 |
+
r, g, b = COLORS_BY_NAME[value_lower]
|
| 303 |
+
except KeyError:
|
| 304 |
+
pass
|
| 305 |
+
else:
|
| 306 |
+
return ints_to_rgba(r, g, b, None)
|
| 307 |
+
|
| 308 |
+
m = re.fullmatch(r_hex_short, value_lower)
|
| 309 |
+
if m:
|
| 310 |
+
*rgb, a = m.groups()
|
| 311 |
+
r, g, b = (int(v * 2, 16) for v in rgb)
|
| 312 |
+
if a:
|
| 313 |
+
alpha: Optional[float] = int(a * 2, 16) / 255
|
| 314 |
+
else:
|
| 315 |
+
alpha = None
|
| 316 |
+
return ints_to_rgba(r, g, b, alpha)
|
| 317 |
+
|
| 318 |
+
m = re.fullmatch(r_hex_long, value_lower)
|
| 319 |
+
if m:
|
| 320 |
+
*rgb, a = m.groups()
|
| 321 |
+
r, g, b = (int(v, 16) for v in rgb)
|
| 322 |
+
if a:
|
| 323 |
+
alpha = int(a, 16) / 255
|
| 324 |
+
else:
|
| 325 |
+
alpha = None
|
| 326 |
+
return ints_to_rgba(r, g, b, alpha)
|
| 327 |
+
|
| 328 |
+
m = re.fullmatch(r_rgb, value_lower) or re.fullmatch(r_rgb_v4_style, value_lower)
|
| 329 |
+
if m:
|
| 330 |
+
return ints_to_rgba(*m.groups()) # type: ignore
|
| 331 |
+
|
| 332 |
+
m = re.fullmatch(r_hsl, value_lower) or re.fullmatch(r_hsl_v4_style, value_lower)
|
| 333 |
+
if m:
|
| 334 |
+
return parse_hsl(*m.groups()) # type: ignore
|
| 335 |
+
|
| 336 |
+
raise PydanticCustomError('color_error', 'value is not a valid color: string not recognised as a valid color')
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def ints_to_rgba(r: Union[int, str], g: Union[int, str], b: Union[int, str], alpha: Optional[float] = None) -> RGBA:
|
| 340 |
+
"""Converts integer or string values for RGB color and an optional alpha value to an `RGBA` object.
|
| 341 |
+
|
| 342 |
+
Args:
|
| 343 |
+
r: An integer or string representing the red color value.
|
| 344 |
+
g: An integer or string representing the green color value.
|
| 345 |
+
b: An integer or string representing the blue color value.
|
| 346 |
+
alpha: A float representing the alpha value. Defaults to None.
|
| 347 |
+
|
| 348 |
+
Returns:
|
| 349 |
+
An instance of the `RGBA` class with the corresponding color and alpha values.
|
| 350 |
+
"""
|
| 351 |
+
return RGBA(parse_color_value(r), parse_color_value(g), parse_color_value(b), parse_float_alpha(alpha))
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def parse_color_value(value: Union[int, str], max_val: int = 255) -> float:
|
| 355 |
+
"""Parse the color value provided and return a number between 0 and 1.
|
| 356 |
+
|
| 357 |
+
Args:
|
| 358 |
+
value: An integer or string color value.
|
| 359 |
+
max_val: Maximum range value. Defaults to 255.
|
| 360 |
+
|
| 361 |
+
Raises:
|
| 362 |
+
PydanticCustomError: If the value is not a valid color.
|
| 363 |
+
|
| 364 |
+
Returns:
|
| 365 |
+
A number between 0 and 1.
|
| 366 |
+
"""
|
| 367 |
+
try:
|
| 368 |
+
color = float(value)
|
| 369 |
+
except ValueError:
|
| 370 |
+
raise PydanticCustomError('color_error', 'value is not a valid color: color values must be a valid number')
|
| 371 |
+
if 0 <= color <= max_val:
|
| 372 |
+
return color / max_val
|
| 373 |
+
else:
|
| 374 |
+
raise PydanticCustomError(
|
| 375 |
+
'color_error',
|
| 376 |
+
'value is not a valid color: color values must be in the range 0 to {max_val}',
|
| 377 |
+
{'max_val': max_val},
|
| 378 |
+
)
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
def parse_float_alpha(value: Union[None, str, float, int]) -> Optional[float]:
|
| 382 |
+
"""Parse an alpha value checking it's a valid float in the range 0 to 1.
|
| 383 |
+
|
| 384 |
+
Args:
|
| 385 |
+
value: The input value to parse.
|
| 386 |
+
|
| 387 |
+
Returns:
|
| 388 |
+
The parsed value as a float, or `None` if the value was None or equal 1.
|
| 389 |
+
|
| 390 |
+
Raises:
|
| 391 |
+
PydanticCustomError: If the input value cannot be successfully parsed as a float in the expected range.
|
| 392 |
+
"""
|
| 393 |
+
if value is None:
|
| 394 |
+
return None
|
| 395 |
+
try:
|
| 396 |
+
if isinstance(value, str) and value.endswith('%'):
|
| 397 |
+
alpha = float(value[:-1]) / 100
|
| 398 |
+
else:
|
| 399 |
+
alpha = float(value)
|
| 400 |
+
except ValueError:
|
| 401 |
+
raise PydanticCustomError('color_error', 'value is not a valid color: alpha values must be a valid float')
|
| 402 |
+
|
| 403 |
+
if math.isclose(alpha, 1):
|
| 404 |
+
return None
|
| 405 |
+
elif 0 <= alpha <= 1:
|
| 406 |
+
return alpha
|
| 407 |
+
else:
|
| 408 |
+
raise PydanticCustomError('color_error', 'value is not a valid color: alpha values must be in the range 0 to 1')
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def parse_hsl(h: str, h_units: str, sat: str, light: str, alpha: Optional[float] = None) -> RGBA:
|
| 412 |
+
"""Parse raw hue, saturation, lightness, and alpha values and convert to RGBA.
|
| 413 |
+
|
| 414 |
+
Args:
|
| 415 |
+
h: The hue value.
|
| 416 |
+
h_units: The unit for hue value.
|
| 417 |
+
sat: The saturation value.
|
| 418 |
+
light: The lightness value.
|
| 419 |
+
alpha: Alpha value.
|
| 420 |
+
|
| 421 |
+
Returns:
|
| 422 |
+
An instance of `RGBA`.
|
| 423 |
+
"""
|
| 424 |
+
s_value, l_value = parse_color_value(sat, 100), parse_color_value(light, 100)
|
| 425 |
+
|
| 426 |
+
h_value = float(h)
|
| 427 |
+
if h_units in {None, 'deg'}:
|
| 428 |
+
h_value = h_value % 360 / 360
|
| 429 |
+
elif h_units == 'rad':
|
| 430 |
+
h_value = h_value % rads / rads
|
| 431 |
+
else:
|
| 432 |
+
# turns
|
| 433 |
+
h_value = h_value % 1
|
| 434 |
+
|
| 435 |
+
r, g, b = hls_to_rgb(h_value, l_value, s_value)
|
| 436 |
+
return RGBA(r, g, b, parse_float_alpha(alpha))
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def float_to_255(c: float) -> int:
|
| 440 |
+
"""Converts a float value between 0 and 1 (inclusive) to an integer between 0 and 255 (inclusive).
|
| 441 |
+
|
| 442 |
+
Args:
|
| 443 |
+
c: The float value to be converted. Must be between 0 and 1 (inclusive).
|
| 444 |
+
|
| 445 |
+
Returns:
|
| 446 |
+
The integer equivalent of the given float value rounded to the nearest whole number.
|
| 447 |
+
|
| 448 |
+
Raises:
|
| 449 |
+
ValueError: If the given float value is outside the acceptable range of 0 to 1 (inclusive).
|
| 450 |
+
"""
|
| 451 |
+
return int(round(c * 255))
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
COLORS_BY_NAME = {
|
| 455 |
+
'aliceblue': (240, 248, 255),
|
| 456 |
+
'antiquewhite': (250, 235, 215),
|
| 457 |
+
'aqua': (0, 255, 255),
|
| 458 |
+
'aquamarine': (127, 255, 212),
|
| 459 |
+
'azure': (240, 255, 255),
|
| 460 |
+
'beige': (245, 245, 220),
|
| 461 |
+
'bisque': (255, 228, 196),
|
| 462 |
+
'black': (0, 0, 0),
|
| 463 |
+
'blanchedalmond': (255, 235, 205),
|
| 464 |
+
'blue': (0, 0, 255),
|
| 465 |
+
'blueviolet': (138, 43, 226),
|
| 466 |
+
'brown': (165, 42, 42),
|
| 467 |
+
'burlywood': (222, 184, 135),
|
| 468 |
+
'cadetblue': (95, 158, 160),
|
| 469 |
+
'chartreuse': (127, 255, 0),
|
| 470 |
+
'chocolate': (210, 105, 30),
|
| 471 |
+
'coral': (255, 127, 80),
|
| 472 |
+
'cornflowerblue': (100, 149, 237),
|
| 473 |
+
'cornsilk': (255, 248, 220),
|
| 474 |
+
'crimson': (220, 20, 60),
|
| 475 |
+
'cyan': (0, 255, 255),
|
| 476 |
+
'darkblue': (0, 0, 139),
|
| 477 |
+
'darkcyan': (0, 139, 139),
|
| 478 |
+
'darkgoldenrod': (184, 134, 11),
|
| 479 |
+
'darkgray': (169, 169, 169),
|
| 480 |
+
'darkgreen': (0, 100, 0),
|
| 481 |
+
'darkgrey': (169, 169, 169),
|
| 482 |
+
'darkkhaki': (189, 183, 107),
|
| 483 |
+
'darkmagenta': (139, 0, 139),
|
| 484 |
+
'darkolivegreen': (85, 107, 47),
|
| 485 |
+
'darkorange': (255, 140, 0),
|
| 486 |
+
'darkorchid': (153, 50, 204),
|
| 487 |
+
'darkred': (139, 0, 0),
|
| 488 |
+
'darksalmon': (233, 150, 122),
|
| 489 |
+
'darkseagreen': (143, 188, 143),
|
| 490 |
+
'darkslateblue': (72, 61, 139),
|
| 491 |
+
'darkslategray': (47, 79, 79),
|
| 492 |
+
'darkslategrey': (47, 79, 79),
|
| 493 |
+
'darkturquoise': (0, 206, 209),
|
| 494 |
+
'darkviolet': (148, 0, 211),
|
| 495 |
+
'deeppink': (255, 20, 147),
|
| 496 |
+
'deepskyblue': (0, 191, 255),
|
| 497 |
+
'dimgray': (105, 105, 105),
|
| 498 |
+
'dimgrey': (105, 105, 105),
|
| 499 |
+
'dodgerblue': (30, 144, 255),
|
| 500 |
+
'firebrick': (178, 34, 34),
|
| 501 |
+
'floralwhite': (255, 250, 240),
|
| 502 |
+
'forestgreen': (34, 139, 34),
|
| 503 |
+
'fuchsia': (255, 0, 255),
|
| 504 |
+
'gainsboro': (220, 220, 220),
|
| 505 |
+
'ghostwhite': (248, 248, 255),
|
| 506 |
+
'gold': (255, 215, 0),
|
| 507 |
+
'goldenrod': (218, 165, 32),
|
| 508 |
+
'gray': (128, 128, 128),
|
| 509 |
+
'green': (0, 128, 0),
|
| 510 |
+
'greenyellow': (173, 255, 47),
|
| 511 |
+
'grey': (128, 128, 128),
|
| 512 |
+
'honeydew': (240, 255, 240),
|
| 513 |
+
'hotpink': (255, 105, 180),
|
| 514 |
+
'indianred': (205, 92, 92),
|
| 515 |
+
'indigo': (75, 0, 130),
|
| 516 |
+
'ivory': (255, 255, 240),
|
| 517 |
+
'khaki': (240, 230, 140),
|
| 518 |
+
'lavender': (230, 230, 250),
|
| 519 |
+
'lavenderblush': (255, 240, 245),
|
| 520 |
+
'lawngreen': (124, 252, 0),
|
| 521 |
+
'lemonchiffon': (255, 250, 205),
|
| 522 |
+
'lightblue': (173, 216, 230),
|
| 523 |
+
'lightcoral': (240, 128, 128),
|
| 524 |
+
'lightcyan': (224, 255, 255),
|
| 525 |
+
'lightgoldenrodyellow': (250, 250, 210),
|
| 526 |
+
'lightgray': (211, 211, 211),
|
| 527 |
+
'lightgreen': (144, 238, 144),
|
| 528 |
+
'lightgrey': (211, 211, 211),
|
| 529 |
+
'lightpink': (255, 182, 193),
|
| 530 |
+
'lightsalmon': (255, 160, 122),
|
| 531 |
+
'lightseagreen': (32, 178, 170),
|
| 532 |
+
'lightskyblue': (135, 206, 250),
|
| 533 |
+
'lightslategray': (119, 136, 153),
|
| 534 |
+
'lightslategrey': (119, 136, 153),
|
| 535 |
+
'lightsteelblue': (176, 196, 222),
|
| 536 |
+
'lightyellow': (255, 255, 224),
|
| 537 |
+
'lime': (0, 255, 0),
|
| 538 |
+
'limegreen': (50, 205, 50),
|
| 539 |
+
'linen': (250, 240, 230),
|
| 540 |
+
'magenta': (255, 0, 255),
|
| 541 |
+
'maroon': (128, 0, 0),
|
| 542 |
+
'mediumaquamarine': (102, 205, 170),
|
| 543 |
+
'mediumblue': (0, 0, 205),
|
| 544 |
+
'mediumorchid': (186, 85, 211),
|
| 545 |
+
'mediumpurple': (147, 112, 219),
|
| 546 |
+
'mediumseagreen': (60, 179, 113),
|
| 547 |
+
'mediumslateblue': (123, 104, 238),
|
| 548 |
+
'mediumspringgreen': (0, 250, 154),
|
| 549 |
+
'mediumturquoise': (72, 209, 204),
|
| 550 |
+
'mediumvioletred': (199, 21, 133),
|
| 551 |
+
'midnightblue': (25, 25, 112),
|
| 552 |
+
'mintcream': (245, 255, 250),
|
| 553 |
+
'mistyrose': (255, 228, 225),
|
| 554 |
+
'moccasin': (255, 228, 181),
|
| 555 |
+
'navajowhite': (255, 222, 173),
|
| 556 |
+
'navy': (0, 0, 128),
|
| 557 |
+
'oldlace': (253, 245, 230),
|
| 558 |
+
'olive': (128, 128, 0),
|
| 559 |
+
'olivedrab': (107, 142, 35),
|
| 560 |
+
'orange': (255, 165, 0),
|
| 561 |
+
'orangered': (255, 69, 0),
|
| 562 |
+
'orchid': (218, 112, 214),
|
| 563 |
+
'palegoldenrod': (238, 232, 170),
|
| 564 |
+
'palegreen': (152, 251, 152),
|
| 565 |
+
'paleturquoise': (175, 238, 238),
|
| 566 |
+
'palevioletred': (219, 112, 147),
|
| 567 |
+
'papayawhip': (255, 239, 213),
|
| 568 |
+
'peachpuff': (255, 218, 185),
|
| 569 |
+
'peru': (205, 133, 63),
|
| 570 |
+
'pink': (255, 192, 203),
|
| 571 |
+
'plum': (221, 160, 221),
|
| 572 |
+
'powderblue': (176, 224, 230),
|
| 573 |
+
'purple': (128, 0, 128),
|
| 574 |
+
'red': (255, 0, 0),
|
| 575 |
+
'rosybrown': (188, 143, 143),
|
| 576 |
+
'royalblue': (65, 105, 225),
|
| 577 |
+
'saddlebrown': (139, 69, 19),
|
| 578 |
+
'salmon': (250, 128, 114),
|
| 579 |
+
'sandybrown': (244, 164, 96),
|
| 580 |
+
'seagreen': (46, 139, 87),
|
| 581 |
+
'seashell': (255, 245, 238),
|
| 582 |
+
'sienna': (160, 82, 45),
|
| 583 |
+
'silver': (192, 192, 192),
|
| 584 |
+
'skyblue': (135, 206, 235),
|
| 585 |
+
'slateblue': (106, 90, 205),
|
| 586 |
+
'slategray': (112, 128, 144),
|
| 587 |
+
'slategrey': (112, 128, 144),
|
| 588 |
+
'snow': (255, 250, 250),
|
| 589 |
+
'springgreen': (0, 255, 127),
|
| 590 |
+
'steelblue': (70, 130, 180),
|
| 591 |
+
'tan': (210, 180, 140),
|
| 592 |
+
'teal': (0, 128, 128),
|
| 593 |
+
'thistle': (216, 191, 216),
|
| 594 |
+
'tomato': (255, 99, 71),
|
| 595 |
+
'turquoise': (64, 224, 208),
|
| 596 |
+
'violet': (238, 130, 238),
|
| 597 |
+
'wheat': (245, 222, 179),
|
| 598 |
+
'white': (255, 255, 255),
|
| 599 |
+
'whitesmoke': (245, 245, 245),
|
| 600 |
+
'yellow': (255, 255, 0),
|
| 601 |
+
'yellowgreen': (154, 205, 50),
|
| 602 |
+
}
|
| 603 |
+
|
| 604 |
+
COLORS_BY_VALUE = {v: k for k, v in COLORS_BY_NAME.items()}
|
infer_4_37_2/lib/python3.10/site-packages/pydantic/errors.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pydantic-specific errors."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations as _annotations
|
| 4 |
+
|
| 5 |
+
import re
|
| 6 |
+
|
| 7 |
+
from typing_extensions import Literal, Self
|
| 8 |
+
|
| 9 |
+
from ._migration import getattr_migration
|
| 10 |
+
from .version import version_short
|
| 11 |
+
|
| 12 |
+
__all__ = (
|
| 13 |
+
'PydanticUserError',
|
| 14 |
+
'PydanticUndefinedAnnotation',
|
| 15 |
+
'PydanticImportError',
|
| 16 |
+
'PydanticSchemaGenerationError',
|
| 17 |
+
'PydanticInvalidForJsonSchema',
|
| 18 |
+
'PydanticErrorCodes',
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
# We use this URL to allow for future flexibility about how we host the docs, while allowing for Pydantic
|
| 22 |
+
# code in the while with "old" URLs to still work.
|
| 23 |
+
# 'u' refers to "user errors" - e.g. errors caused by developers using pydantic, as opposed to validation errors.
|
| 24 |
+
DEV_ERROR_DOCS_URL = f'https://errors.pydantic.dev/{version_short()}/u/'
|
| 25 |
+
PydanticErrorCodes = Literal[
|
| 26 |
+
'class-not-fully-defined',
|
| 27 |
+
'custom-json-schema',
|
| 28 |
+
'decorator-missing-field',
|
| 29 |
+
'discriminator-no-field',
|
| 30 |
+
'discriminator-alias-type',
|
| 31 |
+
'discriminator-needs-literal',
|
| 32 |
+
'discriminator-alias',
|
| 33 |
+
'discriminator-validator',
|
| 34 |
+
'callable-discriminator-no-tag',
|
| 35 |
+
'typed-dict-version',
|
| 36 |
+
'model-field-overridden',
|
| 37 |
+
'model-field-missing-annotation',
|
| 38 |
+
'config-both',
|
| 39 |
+
'removed-kwargs',
|
| 40 |
+
'circular-reference-schema',
|
| 41 |
+
'invalid-for-json-schema',
|
| 42 |
+
'json-schema-already-used',
|
| 43 |
+
'base-model-instantiated',
|
| 44 |
+
'undefined-annotation',
|
| 45 |
+
'schema-for-unknown-type',
|
| 46 |
+
'import-error',
|
| 47 |
+
'create-model-field-definitions',
|
| 48 |
+
'create-model-config-base',
|
| 49 |
+
'validator-no-fields',
|
| 50 |
+
'validator-invalid-fields',
|
| 51 |
+
'validator-instance-method',
|
| 52 |
+
'validator-input-type',
|
| 53 |
+
'root-validator-pre-skip',
|
| 54 |
+
'model-serializer-instance-method',
|
| 55 |
+
'validator-field-config-info',
|
| 56 |
+
'validator-v1-signature',
|
| 57 |
+
'validator-signature',
|
| 58 |
+
'field-serializer-signature',
|
| 59 |
+
'model-serializer-signature',
|
| 60 |
+
'multiple-field-serializers',
|
| 61 |
+
'invalid-annotated-type',
|
| 62 |
+
'type-adapter-config-unused',
|
| 63 |
+
'root-model-extra',
|
| 64 |
+
'unevaluable-type-annotation',
|
| 65 |
+
'dataclass-init-false-extra-allow',
|
| 66 |
+
'clashing-init-and-init-var',
|
| 67 |
+
'model-config-invalid-field-name',
|
| 68 |
+
'with-config-on-model',
|
| 69 |
+
'dataclass-on-model',
|
| 70 |
+
'validate-call-type',
|
| 71 |
+
'unpack-typed-dict',
|
| 72 |
+
'overlapping-unpack-typed-dict',
|
| 73 |
+
'invalid-self-type',
|
| 74 |
+
]
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class PydanticErrorMixin:
|
| 78 |
+
"""A mixin class for common functionality shared by all Pydantic-specific errors.
|
| 79 |
+
|
| 80 |
+
Attributes:
|
| 81 |
+
message: A message describing the error.
|
| 82 |
+
code: An optional error code from PydanticErrorCodes enum.
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
def __init__(self, message: str, *, code: PydanticErrorCodes | None) -> None:
|
| 86 |
+
self.message = message
|
| 87 |
+
self.code = code
|
| 88 |
+
|
| 89 |
+
def __str__(self) -> str:
|
| 90 |
+
if self.code is None:
|
| 91 |
+
return self.message
|
| 92 |
+
else:
|
| 93 |
+
return f'{self.message}\n\nFor further information visit {DEV_ERROR_DOCS_URL}{self.code}'
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class PydanticUserError(PydanticErrorMixin, TypeError):
|
| 97 |
+
"""An error raised due to incorrect use of Pydantic."""
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class PydanticUndefinedAnnotation(PydanticErrorMixin, NameError):
|
| 101 |
+
"""A subclass of `NameError` raised when handling undefined annotations during `CoreSchema` generation.
|
| 102 |
+
|
| 103 |
+
Attributes:
|
| 104 |
+
name: Name of the error.
|
| 105 |
+
message: Description of the error.
|
| 106 |
+
"""
|
| 107 |
+
|
| 108 |
+
def __init__(self, name: str, message: str) -> None:
|
| 109 |
+
self.name = name
|
| 110 |
+
super().__init__(message=message, code='undefined-annotation')
|
| 111 |
+
|
| 112 |
+
@classmethod
|
| 113 |
+
def from_name_error(cls, name_error: NameError) -> Self:
|
| 114 |
+
"""Convert a `NameError` to a `PydanticUndefinedAnnotation` error.
|
| 115 |
+
|
| 116 |
+
Args:
|
| 117 |
+
name_error: `NameError` to be converted.
|
| 118 |
+
|
| 119 |
+
Returns:
|
| 120 |
+
Converted `PydanticUndefinedAnnotation` error.
|
| 121 |
+
"""
|
| 122 |
+
try:
|
| 123 |
+
name = name_error.name # type: ignore # python > 3.10
|
| 124 |
+
except AttributeError:
|
| 125 |
+
name = re.search(r".*'(.+?)'", str(name_error)).group(1) # type: ignore[union-attr]
|
| 126 |
+
return cls(name=name, message=str(name_error))
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class PydanticImportError(PydanticErrorMixin, ImportError):
|
| 130 |
+
"""An error raised when an import fails due to module changes between V1 and V2.
|
| 131 |
+
|
| 132 |
+
Attributes:
|
| 133 |
+
message: Description of the error.
|
| 134 |
+
"""
|
| 135 |
+
|
| 136 |
+
def __init__(self, message: str) -> None:
|
| 137 |
+
super().__init__(message, code='import-error')
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class PydanticSchemaGenerationError(PydanticUserError):
|
| 141 |
+
"""An error raised during failures to generate a `CoreSchema` for some type.
|
| 142 |
+
|
| 143 |
+
Attributes:
|
| 144 |
+
message: Description of the error.
|
| 145 |
+
"""
|
| 146 |
+
|
| 147 |
+
def __init__(self, message: str) -> None:
|
| 148 |
+
super().__init__(message, code='schema-for-unknown-type')
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class PydanticInvalidForJsonSchema(PydanticUserError):
|
| 152 |
+
"""An error raised during failures to generate a JSON schema for some `CoreSchema`.
|
| 153 |
+
|
| 154 |
+
Attributes:
|
| 155 |
+
message: Description of the error.
|
| 156 |
+
"""
|
| 157 |
+
|
| 158 |
+
def __init__(self, message: str) -> None:
|
| 159 |
+
super().__init__(message, code='invalid-for-json-schema')
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
__getattr__ = getattr_migration(__name__)
|
infer_4_37_2/lib/python3.10/site-packages/pydantic/generics.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The `generics` module is a backport module from V1."""
|
| 2 |
+
|
| 3 |
+
from ._migration import getattr_migration
|
| 4 |
+
|
| 5 |
+
__getattr__ = getattr_migration(__name__)
|
infer_4_37_2/lib/python3.10/site-packages/pydantic/mypy.py
ADDED
|
@@ -0,0 +1,1320 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""This module includes classes and functions designed specifically for use with the mypy plugin."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import sys
|
| 6 |
+
from configparser import ConfigParser
|
| 7 |
+
from typing import Any, Callable, Iterator
|
| 8 |
+
|
| 9 |
+
from mypy.errorcodes import ErrorCode
|
| 10 |
+
from mypy.expandtype import expand_type, expand_type_by_instance
|
| 11 |
+
from mypy.nodes import (
|
| 12 |
+
ARG_NAMED,
|
| 13 |
+
ARG_NAMED_OPT,
|
| 14 |
+
ARG_OPT,
|
| 15 |
+
ARG_POS,
|
| 16 |
+
ARG_STAR2,
|
| 17 |
+
INVARIANT,
|
| 18 |
+
MDEF,
|
| 19 |
+
Argument,
|
| 20 |
+
AssignmentStmt,
|
| 21 |
+
Block,
|
| 22 |
+
CallExpr,
|
| 23 |
+
ClassDef,
|
| 24 |
+
Context,
|
| 25 |
+
Decorator,
|
| 26 |
+
DictExpr,
|
| 27 |
+
EllipsisExpr,
|
| 28 |
+
Expression,
|
| 29 |
+
FuncDef,
|
| 30 |
+
IfStmt,
|
| 31 |
+
JsonDict,
|
| 32 |
+
MemberExpr,
|
| 33 |
+
NameExpr,
|
| 34 |
+
PassStmt,
|
| 35 |
+
PlaceholderNode,
|
| 36 |
+
RefExpr,
|
| 37 |
+
Statement,
|
| 38 |
+
StrExpr,
|
| 39 |
+
SymbolTableNode,
|
| 40 |
+
TempNode,
|
| 41 |
+
TypeAlias,
|
| 42 |
+
TypeInfo,
|
| 43 |
+
Var,
|
| 44 |
+
)
|
| 45 |
+
from mypy.options import Options
|
| 46 |
+
from mypy.plugin import (
|
| 47 |
+
CheckerPluginInterface,
|
| 48 |
+
ClassDefContext,
|
| 49 |
+
MethodContext,
|
| 50 |
+
Plugin,
|
| 51 |
+
ReportConfigContext,
|
| 52 |
+
SemanticAnalyzerPluginInterface,
|
| 53 |
+
)
|
| 54 |
+
from mypy.plugins.common import (
|
| 55 |
+
deserialize_and_fixup_type,
|
| 56 |
+
)
|
| 57 |
+
from mypy.semanal import set_callable_name
|
| 58 |
+
from mypy.server.trigger import make_wildcard_trigger
|
| 59 |
+
from mypy.state import state
|
| 60 |
+
from mypy.typeops import map_type_from_supertype
|
| 61 |
+
from mypy.types import (
|
| 62 |
+
AnyType,
|
| 63 |
+
CallableType,
|
| 64 |
+
Instance,
|
| 65 |
+
NoneType,
|
| 66 |
+
Type,
|
| 67 |
+
TypeOfAny,
|
| 68 |
+
TypeType,
|
| 69 |
+
TypeVarType,
|
| 70 |
+
UnionType,
|
| 71 |
+
get_proper_type,
|
| 72 |
+
)
|
| 73 |
+
from mypy.typevars import fill_typevars
|
| 74 |
+
from mypy.util import get_unique_redefinition_name
|
| 75 |
+
from mypy.version import __version__ as mypy_version
|
| 76 |
+
|
| 77 |
+
from pydantic._internal import _fields
|
| 78 |
+
from pydantic.version import parse_mypy_version
|
| 79 |
+
|
| 80 |
+
CONFIGFILE_KEY = 'pydantic-mypy'
|
| 81 |
+
METADATA_KEY = 'pydantic-mypy-metadata'
|
| 82 |
+
BASEMODEL_FULLNAME = 'pydantic.main.BaseModel'
|
| 83 |
+
BASESETTINGS_FULLNAME = 'pydantic_settings.main.BaseSettings'
|
| 84 |
+
ROOT_MODEL_FULLNAME = 'pydantic.root_model.RootModel'
|
| 85 |
+
MODEL_METACLASS_FULLNAME = 'pydantic._internal._model_construction.ModelMetaclass'
|
| 86 |
+
FIELD_FULLNAME = 'pydantic.fields.Field'
|
| 87 |
+
DATACLASS_FULLNAME = 'pydantic.dataclasses.dataclass'
|
| 88 |
+
MODEL_VALIDATOR_FULLNAME = 'pydantic.functional_validators.model_validator'
|
| 89 |
+
DECORATOR_FULLNAMES = {
|
| 90 |
+
'pydantic.functional_validators.field_validator',
|
| 91 |
+
'pydantic.functional_validators.model_validator',
|
| 92 |
+
'pydantic.functional_serializers.serializer',
|
| 93 |
+
'pydantic.functional_serializers.model_serializer',
|
| 94 |
+
'pydantic.deprecated.class_validators.validator',
|
| 95 |
+
'pydantic.deprecated.class_validators.root_validator',
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
MYPY_VERSION_TUPLE = parse_mypy_version(mypy_version)
|
| 100 |
+
BUILTINS_NAME = 'builtins'
|
| 101 |
+
|
| 102 |
+
# Increment version if plugin changes and mypy caches should be invalidated
|
| 103 |
+
__version__ = 2
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def plugin(version: str) -> type[Plugin]:
|
| 107 |
+
"""`version` is the mypy version string.
|
| 108 |
+
|
| 109 |
+
We might want to use this to print a warning if the mypy version being used is
|
| 110 |
+
newer, or especially older, than we expect (or need).
|
| 111 |
+
|
| 112 |
+
Args:
|
| 113 |
+
version: The mypy version string.
|
| 114 |
+
|
| 115 |
+
Return:
|
| 116 |
+
The Pydantic mypy plugin type.
|
| 117 |
+
"""
|
| 118 |
+
return PydanticPlugin
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class PydanticPlugin(Plugin):
|
| 122 |
+
"""The Pydantic mypy plugin."""
|
| 123 |
+
|
| 124 |
+
def __init__(self, options: Options) -> None:
|
| 125 |
+
self.plugin_config = PydanticPluginConfig(options)
|
| 126 |
+
self._plugin_data = self.plugin_config.to_data()
|
| 127 |
+
super().__init__(options)
|
| 128 |
+
|
| 129 |
+
def get_base_class_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:
|
| 130 |
+
"""Update Pydantic model class."""
|
| 131 |
+
sym = self.lookup_fully_qualified(fullname)
|
| 132 |
+
if sym and isinstance(sym.node, TypeInfo): # pragma: no branch
|
| 133 |
+
# No branching may occur if the mypy cache has not been cleared
|
| 134 |
+
if any(base.fullname == BASEMODEL_FULLNAME for base in sym.node.mro):
|
| 135 |
+
return self._pydantic_model_class_maker_callback
|
| 136 |
+
return None
|
| 137 |
+
|
| 138 |
+
def get_metaclass_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:
|
| 139 |
+
"""Update Pydantic `ModelMetaclass` definition."""
|
| 140 |
+
if fullname == MODEL_METACLASS_FULLNAME:
|
| 141 |
+
return self._pydantic_model_metaclass_marker_callback
|
| 142 |
+
return None
|
| 143 |
+
|
| 144 |
+
def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None:
|
| 145 |
+
"""Adjust return type of `from_orm` method call."""
|
| 146 |
+
if fullname.endswith('.from_orm'):
|
| 147 |
+
return from_attributes_callback
|
| 148 |
+
return None
|
| 149 |
+
|
| 150 |
+
def report_config_data(self, ctx: ReportConfigContext) -> dict[str, Any]:
|
| 151 |
+
"""Return all plugin config data.
|
| 152 |
+
|
| 153 |
+
Used by mypy to determine if cache needs to be discarded.
|
| 154 |
+
"""
|
| 155 |
+
return self._plugin_data
|
| 156 |
+
|
| 157 |
+
def _pydantic_model_class_maker_callback(self, ctx: ClassDefContext) -> None:
|
| 158 |
+
transformer = PydanticModelTransformer(ctx.cls, ctx.reason, ctx.api, self.plugin_config)
|
| 159 |
+
transformer.transform()
|
| 160 |
+
|
| 161 |
+
def _pydantic_model_metaclass_marker_callback(self, ctx: ClassDefContext) -> None:
|
| 162 |
+
"""Reset dataclass_transform_spec attribute of ModelMetaclass.
|
| 163 |
+
|
| 164 |
+
Let the plugin handle it. This behavior can be disabled
|
| 165 |
+
if 'debug_dataclass_transform' is set to True', for testing purposes.
|
| 166 |
+
"""
|
| 167 |
+
if self.plugin_config.debug_dataclass_transform:
|
| 168 |
+
return
|
| 169 |
+
info_metaclass = ctx.cls.info.declared_metaclass
|
| 170 |
+
assert info_metaclass, "callback not passed from 'get_metaclass_hook'"
|
| 171 |
+
if getattr(info_metaclass.type, 'dataclass_transform_spec', None):
|
| 172 |
+
info_metaclass.type.dataclass_transform_spec = None
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
class PydanticPluginConfig:
|
| 176 |
+
"""A Pydantic mypy plugin config holder.
|
| 177 |
+
|
| 178 |
+
Attributes:
|
| 179 |
+
init_forbid_extra: Whether to add a `**kwargs` at the end of the generated `__init__` signature.
|
| 180 |
+
init_typed: Whether to annotate fields in the generated `__init__`.
|
| 181 |
+
warn_required_dynamic_aliases: Whether to raise required dynamic aliases error.
|
| 182 |
+
debug_dataclass_transform: Whether to not reset `dataclass_transform_spec` attribute
|
| 183 |
+
of `ModelMetaclass` for testing purposes.
|
| 184 |
+
"""
|
| 185 |
+
|
| 186 |
+
__slots__ = (
|
| 187 |
+
'init_forbid_extra',
|
| 188 |
+
'init_typed',
|
| 189 |
+
'warn_required_dynamic_aliases',
|
| 190 |
+
'debug_dataclass_transform',
|
| 191 |
+
)
|
| 192 |
+
init_forbid_extra: bool
|
| 193 |
+
init_typed: bool
|
| 194 |
+
warn_required_dynamic_aliases: bool
|
| 195 |
+
debug_dataclass_transform: bool # undocumented
|
| 196 |
+
|
| 197 |
+
def __init__(self, options: Options) -> None:
|
| 198 |
+
if options.config_file is None: # pragma: no cover
|
| 199 |
+
return
|
| 200 |
+
|
| 201 |
+
toml_config = parse_toml(options.config_file)
|
| 202 |
+
if toml_config is not None:
|
| 203 |
+
config = toml_config.get('tool', {}).get('pydantic-mypy', {})
|
| 204 |
+
for key in self.__slots__:
|
| 205 |
+
setting = config.get(key, False)
|
| 206 |
+
if not isinstance(setting, bool):
|
| 207 |
+
raise ValueError(f'Configuration value must be a boolean for key: {key}')
|
| 208 |
+
setattr(self, key, setting)
|
| 209 |
+
else:
|
| 210 |
+
plugin_config = ConfigParser()
|
| 211 |
+
plugin_config.read(options.config_file)
|
| 212 |
+
for key in self.__slots__:
|
| 213 |
+
setting = plugin_config.getboolean(CONFIGFILE_KEY, key, fallback=False)
|
| 214 |
+
setattr(self, key, setting)
|
| 215 |
+
|
| 216 |
+
def to_data(self) -> dict[str, Any]:
|
| 217 |
+
"""Returns a dict of config names to their values."""
|
| 218 |
+
return {key: getattr(self, key) for key in self.__slots__}
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def from_attributes_callback(ctx: MethodContext) -> Type:
|
| 222 |
+
"""Raise an error if from_attributes is not enabled."""
|
| 223 |
+
model_type: Instance
|
| 224 |
+
ctx_type = ctx.type
|
| 225 |
+
if isinstance(ctx_type, TypeType):
|
| 226 |
+
ctx_type = ctx_type.item
|
| 227 |
+
if isinstance(ctx_type, CallableType) and isinstance(ctx_type.ret_type, Instance):
|
| 228 |
+
model_type = ctx_type.ret_type # called on the class
|
| 229 |
+
elif isinstance(ctx_type, Instance):
|
| 230 |
+
model_type = ctx_type # called on an instance (unusual, but still valid)
|
| 231 |
+
else: # pragma: no cover
|
| 232 |
+
detail = f'ctx.type: {ctx_type} (of type {ctx_type.__class__.__name__})'
|
| 233 |
+
error_unexpected_behavior(detail, ctx.api, ctx.context)
|
| 234 |
+
return ctx.default_return_type
|
| 235 |
+
pydantic_metadata = model_type.type.metadata.get(METADATA_KEY)
|
| 236 |
+
if pydantic_metadata is None:
|
| 237 |
+
return ctx.default_return_type
|
| 238 |
+
if not any(base.fullname == BASEMODEL_FULLNAME for base in model_type.type.mro):
|
| 239 |
+
# not a Pydantic v2 model
|
| 240 |
+
return ctx.default_return_type
|
| 241 |
+
from_attributes = pydantic_metadata.get('config', {}).get('from_attributes')
|
| 242 |
+
if from_attributes is not True:
|
| 243 |
+
error_from_attributes(model_type.type.name, ctx.api, ctx.context)
|
| 244 |
+
return ctx.default_return_type
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
class PydanticModelField:
|
| 248 |
+
"""Based on mypy.plugins.dataclasses.DataclassAttribute."""
|
| 249 |
+
|
| 250 |
+
def __init__(
|
| 251 |
+
self,
|
| 252 |
+
name: str,
|
| 253 |
+
alias: str | None,
|
| 254 |
+
is_frozen: bool,
|
| 255 |
+
has_dynamic_alias: bool,
|
| 256 |
+
has_default: bool,
|
| 257 |
+
strict: bool | None,
|
| 258 |
+
line: int,
|
| 259 |
+
column: int,
|
| 260 |
+
type: Type | None,
|
| 261 |
+
info: TypeInfo,
|
| 262 |
+
):
|
| 263 |
+
self.name = name
|
| 264 |
+
self.alias = alias
|
| 265 |
+
self.is_frozen = is_frozen
|
| 266 |
+
self.has_dynamic_alias = has_dynamic_alias
|
| 267 |
+
self.has_default = has_default
|
| 268 |
+
self.strict = strict
|
| 269 |
+
self.line = line
|
| 270 |
+
self.column = column
|
| 271 |
+
self.type = type
|
| 272 |
+
self.info = info
|
| 273 |
+
|
| 274 |
+
def to_argument(
|
| 275 |
+
self,
|
| 276 |
+
current_info: TypeInfo,
|
| 277 |
+
typed: bool,
|
| 278 |
+
model_strict: bool,
|
| 279 |
+
force_optional: bool,
|
| 280 |
+
use_alias: bool,
|
| 281 |
+
api: SemanticAnalyzerPluginInterface,
|
| 282 |
+
force_typevars_invariant: bool,
|
| 283 |
+
is_root_model_root: bool,
|
| 284 |
+
) -> Argument:
|
| 285 |
+
"""Based on mypy.plugins.dataclasses.DataclassAttribute.to_argument."""
|
| 286 |
+
variable = self.to_var(current_info, api, use_alias, force_typevars_invariant)
|
| 287 |
+
|
| 288 |
+
strict = model_strict if self.strict is None else self.strict
|
| 289 |
+
if typed or strict:
|
| 290 |
+
type_annotation = self.expand_type(current_info, api)
|
| 291 |
+
else:
|
| 292 |
+
type_annotation = AnyType(TypeOfAny.explicit)
|
| 293 |
+
|
| 294 |
+
return Argument(
|
| 295 |
+
variable=variable,
|
| 296 |
+
type_annotation=type_annotation,
|
| 297 |
+
initializer=None,
|
| 298 |
+
kind=ARG_OPT
|
| 299 |
+
if is_root_model_root
|
| 300 |
+
else (ARG_NAMED_OPT if force_optional or self.has_default else ARG_NAMED),
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
def expand_type(
|
| 304 |
+
self, current_info: TypeInfo, api: SemanticAnalyzerPluginInterface, force_typevars_invariant: bool = False
|
| 305 |
+
) -> Type | None:
|
| 306 |
+
"""Based on mypy.plugins.dataclasses.DataclassAttribute.expand_type."""
|
| 307 |
+
if force_typevars_invariant:
|
| 308 |
+
# In some cases, mypy will emit an error "Cannot use a covariant type variable as a parameter"
|
| 309 |
+
# To prevent that, we add an option to replace typevars with invariant ones while building certain
|
| 310 |
+
# method signatures (in particular, `__init__`). There may be a better way to do this, if this causes
|
| 311 |
+
# us problems in the future, we should look into why the dataclasses plugin doesn't have this issue.
|
| 312 |
+
if isinstance(self.type, TypeVarType):
|
| 313 |
+
modified_type = self.type.copy_modified()
|
| 314 |
+
modified_type.variance = INVARIANT
|
| 315 |
+
self.type = modified_type
|
| 316 |
+
|
| 317 |
+
if self.type is not None and self.info.self_type is not None:
|
| 318 |
+
# In general, it is not safe to call `expand_type()` during semantic analysis,
|
| 319 |
+
# however this plugin is called very late, so all types should be fully ready.
|
| 320 |
+
# Also, it is tricky to avoid eager expansion of Self types here (e.g. because
|
| 321 |
+
# we serialize attributes).
|
| 322 |
+
with state.strict_optional_set(api.options.strict_optional):
|
| 323 |
+
filled_with_typevars = fill_typevars(current_info)
|
| 324 |
+
# Cannot be TupleType as current_info represents a Pydantic model:
|
| 325 |
+
assert isinstance(filled_with_typevars, Instance)
|
| 326 |
+
if force_typevars_invariant:
|
| 327 |
+
for arg in filled_with_typevars.args:
|
| 328 |
+
if isinstance(arg, TypeVarType):
|
| 329 |
+
arg.variance = INVARIANT
|
| 330 |
+
return expand_type(self.type, {self.info.self_type.id: filled_with_typevars})
|
| 331 |
+
return self.type
|
| 332 |
+
|
| 333 |
+
def to_var(
|
| 334 |
+
self,
|
| 335 |
+
current_info: TypeInfo,
|
| 336 |
+
api: SemanticAnalyzerPluginInterface,
|
| 337 |
+
use_alias: bool,
|
| 338 |
+
force_typevars_invariant: bool = False,
|
| 339 |
+
) -> Var:
|
| 340 |
+
"""Based on mypy.plugins.dataclasses.DataclassAttribute.to_var."""
|
| 341 |
+
if use_alias and self.alias is not None:
|
| 342 |
+
name = self.alias
|
| 343 |
+
else:
|
| 344 |
+
name = self.name
|
| 345 |
+
|
| 346 |
+
return Var(name, self.expand_type(current_info, api, force_typevars_invariant))
|
| 347 |
+
|
| 348 |
+
def serialize(self) -> JsonDict:
|
| 349 |
+
"""Based on mypy.plugins.dataclasses.DataclassAttribute.serialize."""
|
| 350 |
+
assert self.type
|
| 351 |
+
return {
|
| 352 |
+
'name': self.name,
|
| 353 |
+
'alias': self.alias,
|
| 354 |
+
'is_frozen': self.is_frozen,
|
| 355 |
+
'has_dynamic_alias': self.has_dynamic_alias,
|
| 356 |
+
'has_default': self.has_default,
|
| 357 |
+
'strict': self.strict,
|
| 358 |
+
'line': self.line,
|
| 359 |
+
'column': self.column,
|
| 360 |
+
'type': self.type.serialize(),
|
| 361 |
+
}
|
| 362 |
+
|
| 363 |
+
@classmethod
|
| 364 |
+
def deserialize(cls, info: TypeInfo, data: JsonDict, api: SemanticAnalyzerPluginInterface) -> PydanticModelField:
|
| 365 |
+
"""Based on mypy.plugins.dataclasses.DataclassAttribute.deserialize."""
|
| 366 |
+
data = data.copy()
|
| 367 |
+
typ = deserialize_and_fixup_type(data.pop('type'), api)
|
| 368 |
+
return cls(type=typ, info=info, **data)
|
| 369 |
+
|
| 370 |
+
def expand_typevar_from_subtype(self, sub_type: TypeInfo, api: SemanticAnalyzerPluginInterface) -> None:
|
| 371 |
+
"""Expands type vars in the context of a subtype when an attribute is inherited
|
| 372 |
+
from a generic super type.
|
| 373 |
+
"""
|
| 374 |
+
if self.type is not None:
|
| 375 |
+
with state.strict_optional_set(api.options.strict_optional):
|
| 376 |
+
self.type = map_type_from_supertype(self.type, sub_type, self.info)
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
class PydanticModelClassVar:
|
| 380 |
+
"""Based on mypy.plugins.dataclasses.DataclassAttribute.
|
| 381 |
+
|
| 382 |
+
ClassVars are ignored by subclasses.
|
| 383 |
+
|
| 384 |
+
Attributes:
|
| 385 |
+
name: the ClassVar name
|
| 386 |
+
"""
|
| 387 |
+
|
| 388 |
+
def __init__(self, name):
|
| 389 |
+
self.name = name
|
| 390 |
+
|
| 391 |
+
@classmethod
|
| 392 |
+
def deserialize(cls, data: JsonDict) -> PydanticModelClassVar:
|
| 393 |
+
"""Based on mypy.plugins.dataclasses.DataclassAttribute.deserialize."""
|
| 394 |
+
data = data.copy()
|
| 395 |
+
return cls(**data)
|
| 396 |
+
|
| 397 |
+
def serialize(self) -> JsonDict:
|
| 398 |
+
"""Based on mypy.plugins.dataclasses.DataclassAttribute.serialize."""
|
| 399 |
+
return {
|
| 400 |
+
'name': self.name,
|
| 401 |
+
}
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
class PydanticModelTransformer:
|
| 405 |
+
"""Transform the BaseModel subclass according to the plugin settings.
|
| 406 |
+
|
| 407 |
+
Attributes:
|
| 408 |
+
tracked_config_fields: A set of field configs that the plugin has to track their value.
|
| 409 |
+
"""
|
| 410 |
+
|
| 411 |
+
tracked_config_fields: set[str] = {
|
| 412 |
+
'extra',
|
| 413 |
+
'frozen',
|
| 414 |
+
'from_attributes',
|
| 415 |
+
'populate_by_name',
|
| 416 |
+
'alias_generator',
|
| 417 |
+
'strict',
|
| 418 |
+
}
|
| 419 |
+
|
| 420 |
+
def __init__(
|
| 421 |
+
self,
|
| 422 |
+
cls: ClassDef,
|
| 423 |
+
reason: Expression | Statement,
|
| 424 |
+
api: SemanticAnalyzerPluginInterface,
|
| 425 |
+
plugin_config: PydanticPluginConfig,
|
| 426 |
+
) -> None:
|
| 427 |
+
self._cls = cls
|
| 428 |
+
self._reason = reason
|
| 429 |
+
self._api = api
|
| 430 |
+
|
| 431 |
+
self.plugin_config = plugin_config
|
| 432 |
+
|
| 433 |
+
def transform(self) -> bool:
|
| 434 |
+
"""Configures the BaseModel subclass according to the plugin settings.
|
| 435 |
+
|
| 436 |
+
In particular:
|
| 437 |
+
|
| 438 |
+
* determines the model config and fields,
|
| 439 |
+
* adds a fields-aware signature for the initializer and construct methods
|
| 440 |
+
* freezes the class if frozen = True
|
| 441 |
+
* stores the fields, config, and if the class is settings in the mypy metadata for access by subclasses
|
| 442 |
+
"""
|
| 443 |
+
info = self._cls.info
|
| 444 |
+
is_root_model = any(ROOT_MODEL_FULLNAME in base.fullname for base in info.mro[:-1])
|
| 445 |
+
config = self.collect_config()
|
| 446 |
+
fields, class_vars = self.collect_fields_and_class_vars(config, is_root_model)
|
| 447 |
+
if fields is None or class_vars is None:
|
| 448 |
+
# Some definitions are not ready. We need another pass.
|
| 449 |
+
return False
|
| 450 |
+
for field in fields:
|
| 451 |
+
if field.type is None:
|
| 452 |
+
return False
|
| 453 |
+
|
| 454 |
+
is_settings = any(base.fullname == BASESETTINGS_FULLNAME for base in info.mro[:-1])
|
| 455 |
+
self.add_initializer(fields, config, is_settings, is_root_model)
|
| 456 |
+
self.add_model_construct_method(fields, config, is_settings, is_root_model)
|
| 457 |
+
self.set_frozen(fields, self._api, frozen=config.frozen is True)
|
| 458 |
+
|
| 459 |
+
self.adjust_decorator_signatures()
|
| 460 |
+
|
| 461 |
+
info.metadata[METADATA_KEY] = {
|
| 462 |
+
'fields': {field.name: field.serialize() for field in fields},
|
| 463 |
+
'class_vars': {class_var.name: class_var.serialize() for class_var in class_vars},
|
| 464 |
+
'config': config.get_values_dict(),
|
| 465 |
+
}
|
| 466 |
+
|
| 467 |
+
return True
|
| 468 |
+
|
| 469 |
+
def adjust_decorator_signatures(self) -> None:
|
| 470 |
+
"""When we decorate a function `f` with `pydantic.validator(...)`, `pydantic.field_validator`
|
| 471 |
+
or `pydantic.serializer(...)`, mypy sees `f` as a regular method taking a `self` instance,
|
| 472 |
+
even though pydantic internally wraps `f` with `classmethod` if necessary.
|
| 473 |
+
|
| 474 |
+
Teach mypy this by marking any function whose outermost decorator is a `validator()`,
|
| 475 |
+
`field_validator()` or `serializer()` call as a `classmethod`.
|
| 476 |
+
"""
|
| 477 |
+
for sym in self._cls.info.names.values():
|
| 478 |
+
if isinstance(sym.node, Decorator):
|
| 479 |
+
first_dec = sym.node.original_decorators[0]
|
| 480 |
+
if (
|
| 481 |
+
isinstance(first_dec, CallExpr)
|
| 482 |
+
and isinstance(first_dec.callee, NameExpr)
|
| 483 |
+
and first_dec.callee.fullname in DECORATOR_FULLNAMES
|
| 484 |
+
# @model_validator(mode="after") is an exception, it expects a regular method
|
| 485 |
+
and not (
|
| 486 |
+
first_dec.callee.fullname == MODEL_VALIDATOR_FULLNAME
|
| 487 |
+
and any(
|
| 488 |
+
first_dec.arg_names[i] == 'mode' and isinstance(arg, StrExpr) and arg.value == 'after'
|
| 489 |
+
for i, arg in enumerate(first_dec.args)
|
| 490 |
+
)
|
| 491 |
+
)
|
| 492 |
+
):
|
| 493 |
+
# TODO: Only do this if the first argument of the decorated function is `cls`
|
| 494 |
+
sym.node.func.is_class = True
|
| 495 |
+
|
| 496 |
+
def collect_config(self) -> ModelConfigData: # noqa: C901 (ignore complexity)
|
| 497 |
+
"""Collects the values of the config attributes that are used by the plugin, accounting for parent classes."""
|
| 498 |
+
cls = self._cls
|
| 499 |
+
config = ModelConfigData()
|
| 500 |
+
|
| 501 |
+
has_config_kwargs = False
|
| 502 |
+
has_config_from_namespace = False
|
| 503 |
+
|
| 504 |
+
# Handle `class MyModel(BaseModel, <name>=<expr>, ...):`
|
| 505 |
+
for name, expr in cls.keywords.items():
|
| 506 |
+
config_data = self.get_config_update(name, expr)
|
| 507 |
+
if config_data:
|
| 508 |
+
has_config_kwargs = True
|
| 509 |
+
config.update(config_data)
|
| 510 |
+
|
| 511 |
+
# Handle `model_config`
|
| 512 |
+
stmt: Statement | None = None
|
| 513 |
+
for stmt in cls.defs.body:
|
| 514 |
+
if not isinstance(stmt, (AssignmentStmt, ClassDef)):
|
| 515 |
+
continue
|
| 516 |
+
|
| 517 |
+
if isinstance(stmt, AssignmentStmt):
|
| 518 |
+
lhs = stmt.lvalues[0]
|
| 519 |
+
if not isinstance(lhs, NameExpr) or lhs.name != 'model_config':
|
| 520 |
+
continue
|
| 521 |
+
|
| 522 |
+
if isinstance(stmt.rvalue, CallExpr): # calls to `dict` or `ConfigDict`
|
| 523 |
+
for arg_name, arg in zip(stmt.rvalue.arg_names, stmt.rvalue.args):
|
| 524 |
+
if arg_name is None:
|
| 525 |
+
continue
|
| 526 |
+
config.update(self.get_config_update(arg_name, arg, lax_extra=True))
|
| 527 |
+
elif isinstance(stmt.rvalue, DictExpr): # dict literals
|
| 528 |
+
for key_expr, value_expr in stmt.rvalue.items:
|
| 529 |
+
if not isinstance(key_expr, StrExpr):
|
| 530 |
+
continue
|
| 531 |
+
config.update(self.get_config_update(key_expr.value, value_expr))
|
| 532 |
+
|
| 533 |
+
elif isinstance(stmt, ClassDef):
|
| 534 |
+
if stmt.name != 'Config': # 'deprecated' Config-class
|
| 535 |
+
continue
|
| 536 |
+
for substmt in stmt.defs.body:
|
| 537 |
+
if not isinstance(substmt, AssignmentStmt):
|
| 538 |
+
continue
|
| 539 |
+
lhs = substmt.lvalues[0]
|
| 540 |
+
if not isinstance(lhs, NameExpr):
|
| 541 |
+
continue
|
| 542 |
+
config.update(self.get_config_update(lhs.name, substmt.rvalue))
|
| 543 |
+
|
| 544 |
+
if has_config_kwargs:
|
| 545 |
+
self._api.fail(
|
| 546 |
+
'Specifying config in two places is ambiguous, use either Config attribute or class kwargs',
|
| 547 |
+
cls,
|
| 548 |
+
)
|
| 549 |
+
break
|
| 550 |
+
|
| 551 |
+
has_config_from_namespace = True
|
| 552 |
+
|
| 553 |
+
if has_config_kwargs or has_config_from_namespace:
|
| 554 |
+
if (
|
| 555 |
+
stmt
|
| 556 |
+
and config.has_alias_generator
|
| 557 |
+
and not config.populate_by_name
|
| 558 |
+
and self.plugin_config.warn_required_dynamic_aliases
|
| 559 |
+
):
|
| 560 |
+
error_required_dynamic_aliases(self._api, stmt)
|
| 561 |
+
|
| 562 |
+
for info in cls.info.mro[1:]: # 0 is the current class
|
| 563 |
+
if METADATA_KEY not in info.metadata:
|
| 564 |
+
continue
|
| 565 |
+
|
| 566 |
+
# Each class depends on the set of fields in its ancestors
|
| 567 |
+
self._api.add_plugin_dependency(make_wildcard_trigger(info.fullname))
|
| 568 |
+
for name, value in info.metadata[METADATA_KEY]['config'].items():
|
| 569 |
+
config.setdefault(name, value)
|
| 570 |
+
return config
|
| 571 |
+
|
| 572 |
+
def collect_fields_and_class_vars(
|
| 573 |
+
self, model_config: ModelConfigData, is_root_model: bool
|
| 574 |
+
) -> tuple[list[PydanticModelField] | None, list[PydanticModelClassVar] | None]:
|
| 575 |
+
"""Collects the fields for the model, accounting for parent classes."""
|
| 576 |
+
cls = self._cls
|
| 577 |
+
|
| 578 |
+
# First, collect fields and ClassVars belonging to any class in the MRO, ignoring duplicates.
|
| 579 |
+
#
|
| 580 |
+
# We iterate through the MRO in reverse because attrs defined in the parent must appear
|
| 581 |
+
# earlier in the attributes list than attrs defined in the child. See:
|
| 582 |
+
# https://docs.python.org/3/library/dataclasses.html#inheritance
|
| 583 |
+
#
|
| 584 |
+
# However, we also want fields defined in the subtype to override ones defined
|
| 585 |
+
# in the parent. We can implement this via a dict without disrupting the attr order
|
| 586 |
+
# because dicts preserve insertion order in Python 3.7+.
|
| 587 |
+
found_fields: dict[str, PydanticModelField] = {}
|
| 588 |
+
found_class_vars: dict[str, PydanticModelClassVar] = {}
|
| 589 |
+
for info in reversed(cls.info.mro[1:-1]): # 0 is the current class, -2 is BaseModel, -1 is object
|
| 590 |
+
# if BASEMODEL_METADATA_TAG_KEY in info.metadata and BASEMODEL_METADATA_KEY not in info.metadata:
|
| 591 |
+
# # We haven't processed the base class yet. Need another pass.
|
| 592 |
+
# return None, None
|
| 593 |
+
if METADATA_KEY not in info.metadata:
|
| 594 |
+
continue
|
| 595 |
+
|
| 596 |
+
# Each class depends on the set of attributes in its dataclass ancestors.
|
| 597 |
+
self._api.add_plugin_dependency(make_wildcard_trigger(info.fullname))
|
| 598 |
+
|
| 599 |
+
for name, data in info.metadata[METADATA_KEY]['fields'].items():
|
| 600 |
+
field = PydanticModelField.deserialize(info, data, self._api)
|
| 601 |
+
# (The following comment comes directly from the dataclasses plugin)
|
| 602 |
+
# TODO: We shouldn't be performing type operations during the main
|
| 603 |
+
# semantic analysis pass, since some TypeInfo attributes might
|
| 604 |
+
# still be in flux. This should be performed in a later phase.
|
| 605 |
+
field.expand_typevar_from_subtype(cls.info, self._api)
|
| 606 |
+
found_fields[name] = field
|
| 607 |
+
|
| 608 |
+
sym_node = cls.info.names.get(name)
|
| 609 |
+
if sym_node and sym_node.node and not isinstance(sym_node.node, Var):
|
| 610 |
+
self._api.fail(
|
| 611 |
+
'BaseModel field may only be overridden by another field',
|
| 612 |
+
sym_node.node,
|
| 613 |
+
)
|
| 614 |
+
# Collect ClassVars
|
| 615 |
+
for name, data in info.metadata[METADATA_KEY]['class_vars'].items():
|
| 616 |
+
found_class_vars[name] = PydanticModelClassVar.deserialize(data)
|
| 617 |
+
|
| 618 |
+
# Second, collect fields and ClassVars belonging to the current class.
|
| 619 |
+
current_field_names: set[str] = set()
|
| 620 |
+
current_class_vars_names: set[str] = set()
|
| 621 |
+
for stmt in self._get_assignment_statements_from_block(cls.defs):
|
| 622 |
+
maybe_field = self.collect_field_or_class_var_from_stmt(stmt, model_config, found_class_vars)
|
| 623 |
+
if maybe_field is None:
|
| 624 |
+
continue
|
| 625 |
+
|
| 626 |
+
lhs = stmt.lvalues[0]
|
| 627 |
+
assert isinstance(lhs, NameExpr) # collect_field_or_class_var_from_stmt guarantees this
|
| 628 |
+
if isinstance(maybe_field, PydanticModelField):
|
| 629 |
+
if is_root_model and lhs.name != 'root':
|
| 630 |
+
error_extra_fields_on_root_model(self._api, stmt)
|
| 631 |
+
else:
|
| 632 |
+
current_field_names.add(lhs.name)
|
| 633 |
+
found_fields[lhs.name] = maybe_field
|
| 634 |
+
elif isinstance(maybe_field, PydanticModelClassVar):
|
| 635 |
+
current_class_vars_names.add(lhs.name)
|
| 636 |
+
found_class_vars[lhs.name] = maybe_field
|
| 637 |
+
|
| 638 |
+
return list(found_fields.values()), list(found_class_vars.values())
|
| 639 |
+
|
| 640 |
+
def _get_assignment_statements_from_if_statement(self, stmt: IfStmt) -> Iterator[AssignmentStmt]:
|
| 641 |
+
for body in stmt.body:
|
| 642 |
+
if not body.is_unreachable:
|
| 643 |
+
yield from self._get_assignment_statements_from_block(body)
|
| 644 |
+
if stmt.else_body is not None and not stmt.else_body.is_unreachable:
|
| 645 |
+
yield from self._get_assignment_statements_from_block(stmt.else_body)
|
| 646 |
+
|
| 647 |
+
def _get_assignment_statements_from_block(self, block: Block) -> Iterator[AssignmentStmt]:
|
| 648 |
+
for stmt in block.body:
|
| 649 |
+
if isinstance(stmt, AssignmentStmt):
|
| 650 |
+
yield stmt
|
| 651 |
+
elif isinstance(stmt, IfStmt):
|
| 652 |
+
yield from self._get_assignment_statements_from_if_statement(stmt)
|
| 653 |
+
|
| 654 |
+
def collect_field_or_class_var_from_stmt( # noqa C901
|
| 655 |
+
self, stmt: AssignmentStmt, model_config: ModelConfigData, class_vars: dict[str, PydanticModelClassVar]
|
| 656 |
+
) -> PydanticModelField | PydanticModelClassVar | None:
|
| 657 |
+
"""Get pydantic model field from statement.
|
| 658 |
+
|
| 659 |
+
Args:
|
| 660 |
+
stmt: The statement.
|
| 661 |
+
model_config: Configuration settings for the model.
|
| 662 |
+
class_vars: ClassVars already known to be defined on the model.
|
| 663 |
+
|
| 664 |
+
Returns:
|
| 665 |
+
A pydantic model field if it could find the field in statement. Otherwise, `None`.
|
| 666 |
+
"""
|
| 667 |
+
cls = self._cls
|
| 668 |
+
|
| 669 |
+
lhs = stmt.lvalues[0]
|
| 670 |
+
if not isinstance(lhs, NameExpr) or not _fields.is_valid_field_name(lhs.name) or lhs.name == 'model_config':
|
| 671 |
+
return None
|
| 672 |
+
|
| 673 |
+
if not stmt.new_syntax:
|
| 674 |
+
if (
|
| 675 |
+
isinstance(stmt.rvalue, CallExpr)
|
| 676 |
+
and isinstance(stmt.rvalue.callee, CallExpr)
|
| 677 |
+
and isinstance(stmt.rvalue.callee.callee, NameExpr)
|
| 678 |
+
and stmt.rvalue.callee.callee.fullname in DECORATOR_FULLNAMES
|
| 679 |
+
):
|
| 680 |
+
# This is a (possibly-reused) validator or serializer, not a field
|
| 681 |
+
# In particular, it looks something like: my_validator = validator('my_field')(f)
|
| 682 |
+
# Eventually, we may want to attempt to respect model_config['ignored_types']
|
| 683 |
+
return None
|
| 684 |
+
|
| 685 |
+
if lhs.name in class_vars:
|
| 686 |
+
# Class vars are not fields and are not required to be annotated
|
| 687 |
+
return None
|
| 688 |
+
|
| 689 |
+
# The assignment does not have an annotation, and it's not anything else we recognize
|
| 690 |
+
error_untyped_fields(self._api, stmt)
|
| 691 |
+
return None
|
| 692 |
+
|
| 693 |
+
lhs = stmt.lvalues[0]
|
| 694 |
+
if not isinstance(lhs, NameExpr):
|
| 695 |
+
return None
|
| 696 |
+
|
| 697 |
+
if not _fields.is_valid_field_name(lhs.name) or lhs.name == 'model_config':
|
| 698 |
+
return None
|
| 699 |
+
|
| 700 |
+
sym = cls.info.names.get(lhs.name)
|
| 701 |
+
if sym is None: # pragma: no cover
|
| 702 |
+
# This is likely due to a star import (see the dataclasses plugin for a more detailed explanation)
|
| 703 |
+
# This is the same logic used in the dataclasses plugin
|
| 704 |
+
return None
|
| 705 |
+
|
| 706 |
+
node = sym.node
|
| 707 |
+
if isinstance(node, PlaceholderNode): # pragma: no cover
|
| 708 |
+
# See the PlaceholderNode docstring for more detail about how this can occur
|
| 709 |
+
# Basically, it is an edge case when dealing with complex import logic
|
| 710 |
+
|
| 711 |
+
# The dataclasses plugin now asserts this cannot happen, but I'd rather not error if it does..
|
| 712 |
+
return None
|
| 713 |
+
|
| 714 |
+
if isinstance(node, TypeAlias):
|
| 715 |
+
self._api.fail(
|
| 716 |
+
'Type aliases inside BaseModel definitions are not supported at runtime',
|
| 717 |
+
node,
|
| 718 |
+
)
|
| 719 |
+
# Skip processing this node. This doesn't match the runtime behaviour,
|
| 720 |
+
# but the only alternative would be to modify the SymbolTable,
|
| 721 |
+
# and it's a little hairy to do that in a plugin.
|
| 722 |
+
return None
|
| 723 |
+
|
| 724 |
+
if not isinstance(node, Var): # pragma: no cover
|
| 725 |
+
# Don't know if this edge case still happens with the `is_valid_field` check above
|
| 726 |
+
# but better safe than sorry
|
| 727 |
+
|
| 728 |
+
# The dataclasses plugin now asserts this cannot happen, but I'd rather not error if it does..
|
| 729 |
+
return None
|
| 730 |
+
|
| 731 |
+
# x: ClassVar[int] is not a field
|
| 732 |
+
if node.is_classvar:
|
| 733 |
+
return PydanticModelClassVar(lhs.name)
|
| 734 |
+
|
| 735 |
+
# x: InitVar[int] is not supported in BaseModel
|
| 736 |
+
node_type = get_proper_type(node.type)
|
| 737 |
+
if isinstance(node_type, Instance) and node_type.type.fullname == 'dataclasses.InitVar':
|
| 738 |
+
self._api.fail(
|
| 739 |
+
'InitVar is not supported in BaseModel',
|
| 740 |
+
node,
|
| 741 |
+
)
|
| 742 |
+
|
| 743 |
+
has_default = self.get_has_default(stmt)
|
| 744 |
+
strict = self.get_strict(stmt)
|
| 745 |
+
|
| 746 |
+
if sym.type is None and node.is_final and node.is_inferred:
|
| 747 |
+
# This follows the logic from the dataclasses plugin. The following comment is taken verbatim:
|
| 748 |
+
#
|
| 749 |
+
# This is a special case, assignment like x: Final = 42 is classified
|
| 750 |
+
# annotated above, but mypy strips the `Final` turning it into x = 42.
|
| 751 |
+
# We do not support inferred types in dataclasses, so we can try inferring
|
| 752 |
+
# type for simple literals, and otherwise require an explicit type
|
| 753 |
+
# argument for Final[...].
|
| 754 |
+
typ = self._api.analyze_simple_literal_type(stmt.rvalue, is_final=True)
|
| 755 |
+
if typ:
|
| 756 |
+
node.type = typ
|
| 757 |
+
else:
|
| 758 |
+
self._api.fail(
|
| 759 |
+
'Need type argument for Final[...] with non-literal default in BaseModel',
|
| 760 |
+
stmt,
|
| 761 |
+
)
|
| 762 |
+
node.type = AnyType(TypeOfAny.from_error)
|
| 763 |
+
|
| 764 |
+
alias, has_dynamic_alias = self.get_alias_info(stmt)
|
| 765 |
+
if has_dynamic_alias and not model_config.populate_by_name and self.plugin_config.warn_required_dynamic_aliases:
|
| 766 |
+
error_required_dynamic_aliases(self._api, stmt)
|
| 767 |
+
is_frozen = self.is_field_frozen(stmt)
|
| 768 |
+
|
| 769 |
+
init_type = self._infer_dataclass_attr_init_type(sym, lhs.name, stmt)
|
| 770 |
+
return PydanticModelField(
|
| 771 |
+
name=lhs.name,
|
| 772 |
+
has_dynamic_alias=has_dynamic_alias,
|
| 773 |
+
has_default=has_default,
|
| 774 |
+
strict=strict,
|
| 775 |
+
alias=alias,
|
| 776 |
+
is_frozen=is_frozen,
|
| 777 |
+
line=stmt.line,
|
| 778 |
+
column=stmt.column,
|
| 779 |
+
type=init_type,
|
| 780 |
+
info=cls.info,
|
| 781 |
+
)
|
| 782 |
+
|
| 783 |
+
def _infer_dataclass_attr_init_type(self, sym: SymbolTableNode, name: str, context: Context) -> Type | None:
|
| 784 |
+
"""Infer __init__ argument type for an attribute.
|
| 785 |
+
|
| 786 |
+
In particular, possibly use the signature of __set__.
|
| 787 |
+
"""
|
| 788 |
+
default = sym.type
|
| 789 |
+
if sym.implicit:
|
| 790 |
+
return default
|
| 791 |
+
t = get_proper_type(sym.type)
|
| 792 |
+
|
| 793 |
+
# Perform a simple-minded inference from the signature of __set__, if present.
|
| 794 |
+
# We can't use mypy.checkmember here, since this plugin runs before type checking.
|
| 795 |
+
# We only support some basic scanerios here, which is hopefully sufficient for
|
| 796 |
+
# the vast majority of use cases.
|
| 797 |
+
if not isinstance(t, Instance):
|
| 798 |
+
return default
|
| 799 |
+
setter = t.type.get('__set__')
|
| 800 |
+
if setter:
|
| 801 |
+
if isinstance(setter.node, FuncDef):
|
| 802 |
+
super_info = t.type.get_containing_type_info('__set__')
|
| 803 |
+
assert super_info
|
| 804 |
+
if setter.type:
|
| 805 |
+
setter_type = get_proper_type(map_type_from_supertype(setter.type, t.type, super_info))
|
| 806 |
+
else:
|
| 807 |
+
return AnyType(TypeOfAny.unannotated)
|
| 808 |
+
if isinstance(setter_type, CallableType) and setter_type.arg_kinds == [
|
| 809 |
+
ARG_POS,
|
| 810 |
+
ARG_POS,
|
| 811 |
+
ARG_POS,
|
| 812 |
+
]:
|
| 813 |
+
return expand_type_by_instance(setter_type.arg_types[2], t)
|
| 814 |
+
else:
|
| 815 |
+
self._api.fail(f'Unsupported signature for "__set__" in "{t.type.name}"', context)
|
| 816 |
+
else:
|
| 817 |
+
self._api.fail(f'Unsupported "__set__" in "{t.type.name}"', context)
|
| 818 |
+
|
| 819 |
+
return default
|
| 820 |
+
|
| 821 |
+
def add_initializer(
|
| 822 |
+
self, fields: list[PydanticModelField], config: ModelConfigData, is_settings: bool, is_root_model: bool
|
| 823 |
+
) -> None:
|
| 824 |
+
"""Adds a fields-aware `__init__` method to the class.
|
| 825 |
+
|
| 826 |
+
The added `__init__` will be annotated with types vs. all `Any` depending on the plugin settings.
|
| 827 |
+
"""
|
| 828 |
+
if '__init__' in self._cls.info.names and not self._cls.info.names['__init__'].plugin_generated:
|
| 829 |
+
return # Don't generate an __init__ if one already exists
|
| 830 |
+
|
| 831 |
+
typed = self.plugin_config.init_typed
|
| 832 |
+
model_strict = bool(config.strict)
|
| 833 |
+
use_alias = config.populate_by_name is not True
|
| 834 |
+
requires_dynamic_aliases = bool(config.has_alias_generator and not config.populate_by_name)
|
| 835 |
+
args = self.get_field_arguments(
|
| 836 |
+
fields,
|
| 837 |
+
typed=typed,
|
| 838 |
+
model_strict=model_strict,
|
| 839 |
+
requires_dynamic_aliases=requires_dynamic_aliases,
|
| 840 |
+
use_alias=use_alias,
|
| 841 |
+
is_settings=is_settings,
|
| 842 |
+
is_root_model=is_root_model,
|
| 843 |
+
force_typevars_invariant=True,
|
| 844 |
+
)
|
| 845 |
+
|
| 846 |
+
if is_settings:
|
| 847 |
+
base_settings_node = self._api.lookup_fully_qualified(BASESETTINGS_FULLNAME).node
|
| 848 |
+
assert isinstance(base_settings_node, TypeInfo)
|
| 849 |
+
if '__init__' in base_settings_node.names:
|
| 850 |
+
base_settings_init_node = base_settings_node.names['__init__'].node
|
| 851 |
+
assert isinstance(base_settings_init_node, FuncDef)
|
| 852 |
+
if base_settings_init_node is not None and base_settings_init_node.type is not None:
|
| 853 |
+
func_type = base_settings_init_node.type
|
| 854 |
+
assert isinstance(func_type, CallableType)
|
| 855 |
+
for arg_idx, arg_name in enumerate(func_type.arg_names):
|
| 856 |
+
if arg_name is None or arg_name.startswith('__') or not arg_name.startswith('_'):
|
| 857 |
+
continue
|
| 858 |
+
analyzed_variable_type = self._api.anal_type(func_type.arg_types[arg_idx])
|
| 859 |
+
variable = Var(arg_name, analyzed_variable_type)
|
| 860 |
+
args.append(Argument(variable, analyzed_variable_type, None, ARG_OPT))
|
| 861 |
+
|
| 862 |
+
if not self.should_init_forbid_extra(fields, config):
|
| 863 |
+
var = Var('kwargs')
|
| 864 |
+
args.append(Argument(var, AnyType(TypeOfAny.explicit), None, ARG_STAR2))
|
| 865 |
+
|
| 866 |
+
add_method(self._api, self._cls, '__init__', args=args, return_type=NoneType())
|
| 867 |
+
|
| 868 |
+
def add_model_construct_method(
|
| 869 |
+
self,
|
| 870 |
+
fields: list[PydanticModelField],
|
| 871 |
+
config: ModelConfigData,
|
| 872 |
+
is_settings: bool,
|
| 873 |
+
is_root_model: bool,
|
| 874 |
+
) -> None:
|
| 875 |
+
"""Adds a fully typed `model_construct` classmethod to the class.
|
| 876 |
+
|
| 877 |
+
Similar to the fields-aware __init__ method, but always uses the field names (not aliases),
|
| 878 |
+
and does not treat settings fields as optional.
|
| 879 |
+
"""
|
| 880 |
+
set_str = self._api.named_type(f'{BUILTINS_NAME}.set', [self._api.named_type(f'{BUILTINS_NAME}.str')])
|
| 881 |
+
optional_set_str = UnionType([set_str, NoneType()])
|
| 882 |
+
fields_set_argument = Argument(Var('_fields_set', optional_set_str), optional_set_str, None, ARG_OPT)
|
| 883 |
+
with state.strict_optional_set(self._api.options.strict_optional):
|
| 884 |
+
args = self.get_field_arguments(
|
| 885 |
+
fields,
|
| 886 |
+
typed=True,
|
| 887 |
+
model_strict=bool(config.strict),
|
| 888 |
+
requires_dynamic_aliases=False,
|
| 889 |
+
use_alias=False,
|
| 890 |
+
is_settings=is_settings,
|
| 891 |
+
is_root_model=is_root_model,
|
| 892 |
+
)
|
| 893 |
+
if not self.should_init_forbid_extra(fields, config):
|
| 894 |
+
var = Var('kwargs')
|
| 895 |
+
args.append(Argument(var, AnyType(TypeOfAny.explicit), None, ARG_STAR2))
|
| 896 |
+
|
| 897 |
+
args = args + [fields_set_argument] if is_root_model else [fields_set_argument] + args
|
| 898 |
+
|
| 899 |
+
add_method(
|
| 900 |
+
self._api,
|
| 901 |
+
self._cls,
|
| 902 |
+
'model_construct',
|
| 903 |
+
args=args,
|
| 904 |
+
return_type=fill_typevars(self._cls.info),
|
| 905 |
+
is_classmethod=True,
|
| 906 |
+
)
|
| 907 |
+
|
| 908 |
+
def set_frozen(self, fields: list[PydanticModelField], api: SemanticAnalyzerPluginInterface, frozen: bool) -> None:
|
| 909 |
+
"""Marks all fields as properties so that attempts to set them trigger mypy errors.
|
| 910 |
+
|
| 911 |
+
This is the same approach used by the attrs and dataclasses plugins.
|
| 912 |
+
"""
|
| 913 |
+
info = self._cls.info
|
| 914 |
+
for field in fields:
|
| 915 |
+
sym_node = info.names.get(field.name)
|
| 916 |
+
if sym_node is not None:
|
| 917 |
+
var = sym_node.node
|
| 918 |
+
if isinstance(var, Var):
|
| 919 |
+
var.is_property = frozen or field.is_frozen
|
| 920 |
+
elif isinstance(var, PlaceholderNode) and not self._api.final_iteration:
|
| 921 |
+
# See https://github.com/pydantic/pydantic/issues/5191 to hit this branch for test coverage
|
| 922 |
+
self._api.defer()
|
| 923 |
+
else: # pragma: no cover
|
| 924 |
+
# I don't know whether it's possible to hit this branch, but I've added it for safety
|
| 925 |
+
try:
|
| 926 |
+
var_str = str(var)
|
| 927 |
+
except TypeError:
|
| 928 |
+
# This happens for PlaceholderNode; perhaps it will happen for other types in the future..
|
| 929 |
+
var_str = repr(var)
|
| 930 |
+
detail = f'sym_node.node: {var_str} (of type {var.__class__})'
|
| 931 |
+
error_unexpected_behavior(detail, self._api, self._cls)
|
| 932 |
+
else:
|
| 933 |
+
var = field.to_var(info, api, use_alias=False)
|
| 934 |
+
var.info = info
|
| 935 |
+
var.is_property = frozen
|
| 936 |
+
var._fullname = info.fullname + '.' + var.name
|
| 937 |
+
info.names[var.name] = SymbolTableNode(MDEF, var)
|
| 938 |
+
|
| 939 |
+
def get_config_update(self, name: str, arg: Expression, lax_extra: bool = False) -> ModelConfigData | None:
|
| 940 |
+
"""Determines the config update due to a single kwarg in the ConfigDict definition.
|
| 941 |
+
|
| 942 |
+
Warns if a tracked config attribute is set to a value the plugin doesn't know how to interpret (e.g., an int)
|
| 943 |
+
"""
|
| 944 |
+
if name not in self.tracked_config_fields:
|
| 945 |
+
return None
|
| 946 |
+
if name == 'extra':
|
| 947 |
+
if isinstance(arg, StrExpr):
|
| 948 |
+
forbid_extra = arg.value == 'forbid'
|
| 949 |
+
elif isinstance(arg, MemberExpr):
|
| 950 |
+
forbid_extra = arg.name == 'forbid'
|
| 951 |
+
else:
|
| 952 |
+
if not lax_extra:
|
| 953 |
+
# Only emit an error for other types of `arg` (e.g., `NameExpr`, `ConditionalExpr`, etc.) when
|
| 954 |
+
# reading from a config class, etc. If a ConfigDict is used, then we don't want to emit an error
|
| 955 |
+
# because you'll get type checking from the ConfigDict itself.
|
| 956 |
+
#
|
| 957 |
+
# It would be nice if we could introspect the types better otherwise, but I don't know what the API
|
| 958 |
+
# is to evaluate an expr into its type and then check if that type is compatible with the expected
|
| 959 |
+
# type. Note that you can still get proper type checking via: `model_config = ConfigDict(...)`, just
|
| 960 |
+
# if you don't use an explicit string, the plugin won't be able to infer whether extra is forbidden.
|
| 961 |
+
error_invalid_config_value(name, self._api, arg)
|
| 962 |
+
return None
|
| 963 |
+
return ModelConfigData(forbid_extra=forbid_extra)
|
| 964 |
+
if name == 'alias_generator':
|
| 965 |
+
has_alias_generator = True
|
| 966 |
+
if isinstance(arg, NameExpr) and arg.fullname == 'builtins.None':
|
| 967 |
+
has_alias_generator = False
|
| 968 |
+
return ModelConfigData(has_alias_generator=has_alias_generator)
|
| 969 |
+
if isinstance(arg, NameExpr) and arg.fullname in ('builtins.True', 'builtins.False'):
|
| 970 |
+
return ModelConfigData(**{name: arg.fullname == 'builtins.True'})
|
| 971 |
+
error_invalid_config_value(name, self._api, arg)
|
| 972 |
+
return None
|
| 973 |
+
|
| 974 |
+
@staticmethod
|
| 975 |
+
def get_has_default(stmt: AssignmentStmt) -> bool:
|
| 976 |
+
"""Returns a boolean indicating whether the field defined in `stmt` is a required field."""
|
| 977 |
+
expr = stmt.rvalue
|
| 978 |
+
if isinstance(expr, TempNode):
|
| 979 |
+
# TempNode means annotation-only, so has no default
|
| 980 |
+
return False
|
| 981 |
+
if isinstance(expr, CallExpr) and isinstance(expr.callee, RefExpr) and expr.callee.fullname == FIELD_FULLNAME:
|
| 982 |
+
# The "default value" is a call to `Field`; at this point, the field has a default if and only if:
|
| 983 |
+
# * there is a positional argument that is not `...`
|
| 984 |
+
# * there is a keyword argument named "default" that is not `...`
|
| 985 |
+
# * there is a "default_factory" that is not `None`
|
| 986 |
+
for arg, name in zip(expr.args, expr.arg_names):
|
| 987 |
+
# If name is None, then this arg is the default because it is the only positional argument.
|
| 988 |
+
if name is None or name == 'default':
|
| 989 |
+
return arg.__class__ is not EllipsisExpr
|
| 990 |
+
if name == 'default_factory':
|
| 991 |
+
return not (isinstance(arg, NameExpr) and arg.fullname == 'builtins.None')
|
| 992 |
+
return False
|
| 993 |
+
# Has no default if the "default value" is Ellipsis (i.e., `field_name: Annotation = ...`)
|
| 994 |
+
return not isinstance(expr, EllipsisExpr)
|
| 995 |
+
|
| 996 |
+
@staticmethod
|
| 997 |
+
def get_strict(stmt: AssignmentStmt) -> bool | None:
|
| 998 |
+
"""Returns a the `strict` value of a field if defined, otherwise `None`."""
|
| 999 |
+
expr = stmt.rvalue
|
| 1000 |
+
if isinstance(expr, CallExpr) and isinstance(expr.callee, RefExpr) and expr.callee.fullname == FIELD_FULLNAME:
|
| 1001 |
+
for arg, name in zip(expr.args, expr.arg_names):
|
| 1002 |
+
if name != 'strict':
|
| 1003 |
+
continue
|
| 1004 |
+
if isinstance(arg, NameExpr):
|
| 1005 |
+
if arg.fullname == 'builtins.True':
|
| 1006 |
+
return True
|
| 1007 |
+
elif arg.fullname == 'builtins.False':
|
| 1008 |
+
return False
|
| 1009 |
+
return None
|
| 1010 |
+
return None
|
| 1011 |
+
|
| 1012 |
+
@staticmethod
|
| 1013 |
+
def get_alias_info(stmt: AssignmentStmt) -> tuple[str | None, bool]:
|
| 1014 |
+
"""Returns a pair (alias, has_dynamic_alias), extracted from the declaration of the field defined in `stmt`.
|
| 1015 |
+
|
| 1016 |
+
`has_dynamic_alias` is True if and only if an alias is provided, but not as a string literal.
|
| 1017 |
+
If `has_dynamic_alias` is True, `alias` will be None.
|
| 1018 |
+
"""
|
| 1019 |
+
expr = stmt.rvalue
|
| 1020 |
+
if isinstance(expr, TempNode):
|
| 1021 |
+
# TempNode means annotation-only
|
| 1022 |
+
return None, False
|
| 1023 |
+
|
| 1024 |
+
if not (
|
| 1025 |
+
isinstance(expr, CallExpr) and isinstance(expr.callee, RefExpr) and expr.callee.fullname == FIELD_FULLNAME
|
| 1026 |
+
):
|
| 1027 |
+
# Assigned value is not a call to pydantic.fields.Field
|
| 1028 |
+
return None, False
|
| 1029 |
+
|
| 1030 |
+
for i, arg_name in enumerate(expr.arg_names):
|
| 1031 |
+
if arg_name != 'alias':
|
| 1032 |
+
continue
|
| 1033 |
+
arg = expr.args[i]
|
| 1034 |
+
if isinstance(arg, StrExpr):
|
| 1035 |
+
return arg.value, False
|
| 1036 |
+
else:
|
| 1037 |
+
return None, True
|
| 1038 |
+
return None, False
|
| 1039 |
+
|
| 1040 |
+
@staticmethod
|
| 1041 |
+
def is_field_frozen(stmt: AssignmentStmt) -> bool:
|
| 1042 |
+
"""Returns whether the field is frozen, extracted from the declaration of the field defined in `stmt`.
|
| 1043 |
+
|
| 1044 |
+
Note that this is only whether the field was declared to be frozen in a `<field_name> = Field(frozen=True)`
|
| 1045 |
+
sense; this does not determine whether the field is frozen because the entire model is frozen; that is
|
| 1046 |
+
handled separately.
|
| 1047 |
+
"""
|
| 1048 |
+
expr = stmt.rvalue
|
| 1049 |
+
if isinstance(expr, TempNode):
|
| 1050 |
+
# TempNode means annotation-only
|
| 1051 |
+
return False
|
| 1052 |
+
|
| 1053 |
+
if not (
|
| 1054 |
+
isinstance(expr, CallExpr) and isinstance(expr.callee, RefExpr) and expr.callee.fullname == FIELD_FULLNAME
|
| 1055 |
+
):
|
| 1056 |
+
# Assigned value is not a call to pydantic.fields.Field
|
| 1057 |
+
return False
|
| 1058 |
+
|
| 1059 |
+
for i, arg_name in enumerate(expr.arg_names):
|
| 1060 |
+
if arg_name == 'frozen':
|
| 1061 |
+
arg = expr.args[i]
|
| 1062 |
+
return isinstance(arg, NameExpr) and arg.fullname == 'builtins.True'
|
| 1063 |
+
return False
|
| 1064 |
+
|
| 1065 |
+
def get_field_arguments(
|
| 1066 |
+
self,
|
| 1067 |
+
fields: list[PydanticModelField],
|
| 1068 |
+
typed: bool,
|
| 1069 |
+
model_strict: bool,
|
| 1070 |
+
use_alias: bool,
|
| 1071 |
+
requires_dynamic_aliases: bool,
|
| 1072 |
+
is_settings: bool,
|
| 1073 |
+
is_root_model: bool,
|
| 1074 |
+
force_typevars_invariant: bool = False,
|
| 1075 |
+
) -> list[Argument]:
|
| 1076 |
+
"""Helper function used during the construction of the `__init__` and `model_construct` method signatures.
|
| 1077 |
+
|
| 1078 |
+
Returns a list of mypy Argument instances for use in the generated signatures.
|
| 1079 |
+
"""
|
| 1080 |
+
info = self._cls.info
|
| 1081 |
+
arguments = [
|
| 1082 |
+
field.to_argument(
|
| 1083 |
+
info,
|
| 1084 |
+
typed=typed,
|
| 1085 |
+
model_strict=model_strict,
|
| 1086 |
+
force_optional=requires_dynamic_aliases or is_settings,
|
| 1087 |
+
use_alias=use_alias,
|
| 1088 |
+
api=self._api,
|
| 1089 |
+
force_typevars_invariant=force_typevars_invariant,
|
| 1090 |
+
is_root_model_root=is_root_model and field.name == 'root',
|
| 1091 |
+
)
|
| 1092 |
+
for field in fields
|
| 1093 |
+
if not (use_alias and field.has_dynamic_alias)
|
| 1094 |
+
]
|
| 1095 |
+
return arguments
|
| 1096 |
+
|
| 1097 |
+
def should_init_forbid_extra(self, fields: list[PydanticModelField], config: ModelConfigData) -> bool:
|
| 1098 |
+
"""Indicates whether the generated `__init__` should get a `**kwargs` at the end of its signature.
|
| 1099 |
+
|
| 1100 |
+
We disallow arbitrary kwargs if the extra config setting is "forbid", or if the plugin config says to,
|
| 1101 |
+
*unless* a required dynamic alias is present (since then we can't determine a valid signature).
|
| 1102 |
+
"""
|
| 1103 |
+
if not config.populate_by_name:
|
| 1104 |
+
if self.is_dynamic_alias_present(fields, bool(config.has_alias_generator)):
|
| 1105 |
+
return False
|
| 1106 |
+
if config.forbid_extra:
|
| 1107 |
+
return True
|
| 1108 |
+
return self.plugin_config.init_forbid_extra
|
| 1109 |
+
|
| 1110 |
+
@staticmethod
|
| 1111 |
+
def is_dynamic_alias_present(fields: list[PydanticModelField], has_alias_generator: bool) -> bool:
|
| 1112 |
+
"""Returns whether any fields on the model have a "dynamic alias", i.e., an alias that cannot be
|
| 1113 |
+
determined during static analysis.
|
| 1114 |
+
"""
|
| 1115 |
+
for field in fields:
|
| 1116 |
+
if field.has_dynamic_alias:
|
| 1117 |
+
return True
|
| 1118 |
+
if has_alias_generator:
|
| 1119 |
+
for field in fields:
|
| 1120 |
+
if field.alias is None:
|
| 1121 |
+
return True
|
| 1122 |
+
return False
|
| 1123 |
+
|
| 1124 |
+
|
| 1125 |
+
class ModelConfigData:
|
| 1126 |
+
"""Pydantic mypy plugin model config class."""
|
| 1127 |
+
|
| 1128 |
+
def __init__(
|
| 1129 |
+
self,
|
| 1130 |
+
forbid_extra: bool | None = None,
|
| 1131 |
+
frozen: bool | None = None,
|
| 1132 |
+
from_attributes: bool | None = None,
|
| 1133 |
+
populate_by_name: bool | None = None,
|
| 1134 |
+
has_alias_generator: bool | None = None,
|
| 1135 |
+
strict: bool | None = None,
|
| 1136 |
+
):
|
| 1137 |
+
self.forbid_extra = forbid_extra
|
| 1138 |
+
self.frozen = frozen
|
| 1139 |
+
self.from_attributes = from_attributes
|
| 1140 |
+
self.populate_by_name = populate_by_name
|
| 1141 |
+
self.has_alias_generator = has_alias_generator
|
| 1142 |
+
self.strict = strict
|
| 1143 |
+
|
| 1144 |
+
def get_values_dict(self) -> dict[str, Any]:
|
| 1145 |
+
"""Returns a dict of Pydantic model config names to their values.
|
| 1146 |
+
|
| 1147 |
+
It includes the config if config value is not `None`.
|
| 1148 |
+
"""
|
| 1149 |
+
return {k: v for k, v in self.__dict__.items() if v is not None}
|
| 1150 |
+
|
| 1151 |
+
def update(self, config: ModelConfigData | None) -> None:
|
| 1152 |
+
"""Update Pydantic model config values."""
|
| 1153 |
+
if config is None:
|
| 1154 |
+
return
|
| 1155 |
+
for k, v in config.get_values_dict().items():
|
| 1156 |
+
setattr(self, k, v)
|
| 1157 |
+
|
| 1158 |
+
def setdefault(self, key: str, value: Any) -> None:
|
| 1159 |
+
"""Set default value for Pydantic model config if config value is `None`."""
|
| 1160 |
+
if getattr(self, key) is None:
|
| 1161 |
+
setattr(self, key, value)
|
| 1162 |
+
|
| 1163 |
+
|
| 1164 |
+
ERROR_ORM = ErrorCode('pydantic-orm', 'Invalid from_attributes call', 'Pydantic')
|
| 1165 |
+
ERROR_CONFIG = ErrorCode('pydantic-config', 'Invalid config value', 'Pydantic')
|
| 1166 |
+
ERROR_ALIAS = ErrorCode('pydantic-alias', 'Dynamic alias disallowed', 'Pydantic')
|
| 1167 |
+
ERROR_UNEXPECTED = ErrorCode('pydantic-unexpected', 'Unexpected behavior', 'Pydantic')
|
| 1168 |
+
ERROR_UNTYPED = ErrorCode('pydantic-field', 'Untyped field disallowed', 'Pydantic')
|
| 1169 |
+
ERROR_FIELD_DEFAULTS = ErrorCode('pydantic-field', 'Invalid Field defaults', 'Pydantic')
|
| 1170 |
+
ERROR_EXTRA_FIELD_ROOT_MODEL = ErrorCode('pydantic-field', 'Extra field on RootModel subclass', 'Pydantic')
|
| 1171 |
+
|
| 1172 |
+
|
| 1173 |
+
def error_from_attributes(model_name: str, api: CheckerPluginInterface, context: Context) -> None:
|
| 1174 |
+
"""Emits an error when the model does not have `from_attributes=True`."""
|
| 1175 |
+
api.fail(f'"{model_name}" does not have from_attributes=True', context, code=ERROR_ORM)
|
| 1176 |
+
|
| 1177 |
+
|
| 1178 |
+
def error_invalid_config_value(name: str, api: SemanticAnalyzerPluginInterface, context: Context) -> None:
|
| 1179 |
+
"""Emits an error when the config value is invalid."""
|
| 1180 |
+
api.fail(f'Invalid value for "Config.{name}"', context, code=ERROR_CONFIG)
|
| 1181 |
+
|
| 1182 |
+
|
| 1183 |
+
def error_required_dynamic_aliases(api: SemanticAnalyzerPluginInterface, context: Context) -> None:
|
| 1184 |
+
"""Emits required dynamic aliases error.
|
| 1185 |
+
|
| 1186 |
+
This will be called when `warn_required_dynamic_aliases=True`.
|
| 1187 |
+
"""
|
| 1188 |
+
api.fail('Required dynamic aliases disallowed', context, code=ERROR_ALIAS)
|
| 1189 |
+
|
| 1190 |
+
|
| 1191 |
+
def error_unexpected_behavior(
|
| 1192 |
+
detail: str, api: CheckerPluginInterface | SemanticAnalyzerPluginInterface, context: Context
|
| 1193 |
+
) -> None: # pragma: no cover
|
| 1194 |
+
"""Emits unexpected behavior error."""
|
| 1195 |
+
# Can't think of a good way to test this, but I confirmed it renders as desired by adding to a non-error path
|
| 1196 |
+
link = 'https://github.com/pydantic/pydantic/issues/new/choose'
|
| 1197 |
+
full_message = f'The pydantic mypy plugin ran into unexpected behavior: {detail}\n'
|
| 1198 |
+
full_message += f'Please consider reporting this bug at {link} so we can try to fix it!'
|
| 1199 |
+
api.fail(full_message, context, code=ERROR_UNEXPECTED)
|
| 1200 |
+
|
| 1201 |
+
|
| 1202 |
+
def error_untyped_fields(api: SemanticAnalyzerPluginInterface, context: Context) -> None:
|
| 1203 |
+
"""Emits an error when there is an untyped field in the model."""
|
| 1204 |
+
api.fail('Untyped fields disallowed', context, code=ERROR_UNTYPED)
|
| 1205 |
+
|
| 1206 |
+
|
| 1207 |
+
def error_extra_fields_on_root_model(api: CheckerPluginInterface, context: Context) -> None:
|
| 1208 |
+
"""Emits an error when there is more than just a root field defined for a subclass of RootModel."""
|
| 1209 |
+
api.fail('Only `root` is allowed as a field of a `RootModel`', context, code=ERROR_EXTRA_FIELD_ROOT_MODEL)
|
| 1210 |
+
|
| 1211 |
+
|
| 1212 |
+
def add_method(
|
| 1213 |
+
api: SemanticAnalyzerPluginInterface | CheckerPluginInterface,
|
| 1214 |
+
cls: ClassDef,
|
| 1215 |
+
name: str,
|
| 1216 |
+
args: list[Argument],
|
| 1217 |
+
return_type: Type,
|
| 1218 |
+
self_type: Type | None = None,
|
| 1219 |
+
tvar_def: TypeVarType | None = None,
|
| 1220 |
+
is_classmethod: bool = False,
|
| 1221 |
+
) -> None:
|
| 1222 |
+
"""Very closely related to `mypy.plugins.common.add_method_to_class`, with a few pydantic-specific changes."""
|
| 1223 |
+
info = cls.info
|
| 1224 |
+
|
| 1225 |
+
# First remove any previously generated methods with the same name
|
| 1226 |
+
# to avoid clashes and problems in the semantic analyzer.
|
| 1227 |
+
if name in info.names:
|
| 1228 |
+
sym = info.names[name]
|
| 1229 |
+
if sym.plugin_generated and isinstance(sym.node, FuncDef):
|
| 1230 |
+
cls.defs.body.remove(sym.node) # pragma: no cover
|
| 1231 |
+
|
| 1232 |
+
if isinstance(api, SemanticAnalyzerPluginInterface):
|
| 1233 |
+
function_type = api.named_type('builtins.function')
|
| 1234 |
+
else:
|
| 1235 |
+
function_type = api.named_generic_type('builtins.function', [])
|
| 1236 |
+
|
| 1237 |
+
if is_classmethod:
|
| 1238 |
+
self_type = self_type or TypeType(fill_typevars(info))
|
| 1239 |
+
first = [Argument(Var('_cls'), self_type, None, ARG_POS, True)]
|
| 1240 |
+
else:
|
| 1241 |
+
self_type = self_type or fill_typevars(info)
|
| 1242 |
+
# `self` is positional *ONLY* here, but this can't be expressed
|
| 1243 |
+
# fully in the mypy internal API. ARG_POS is the closest we can get.
|
| 1244 |
+
# Using ARG_POS will, however, give mypy errors if a `self` field
|
| 1245 |
+
# is present on a model:
|
| 1246 |
+
#
|
| 1247 |
+
# Name "self" already defined (possibly by an import) [no-redef]
|
| 1248 |
+
#
|
| 1249 |
+
# As a workaround, we give this argument a name that will
|
| 1250 |
+
# never conflict. By its positional nature, this name will not
|
| 1251 |
+
# be used or exposed to users.
|
| 1252 |
+
first = [Argument(Var('__pydantic_self__'), self_type, None, ARG_POS)]
|
| 1253 |
+
args = first + args
|
| 1254 |
+
|
| 1255 |
+
arg_types, arg_names, arg_kinds = [], [], []
|
| 1256 |
+
for arg in args:
|
| 1257 |
+
assert arg.type_annotation, 'All arguments must be fully typed.'
|
| 1258 |
+
arg_types.append(arg.type_annotation)
|
| 1259 |
+
arg_names.append(arg.variable.name)
|
| 1260 |
+
arg_kinds.append(arg.kind)
|
| 1261 |
+
|
| 1262 |
+
signature = CallableType(arg_types, arg_kinds, arg_names, return_type, function_type)
|
| 1263 |
+
if tvar_def:
|
| 1264 |
+
signature.variables = [tvar_def]
|
| 1265 |
+
|
| 1266 |
+
func = FuncDef(name, args, Block([PassStmt()]))
|
| 1267 |
+
func.info = info
|
| 1268 |
+
func.type = set_callable_name(signature, func)
|
| 1269 |
+
func.is_class = is_classmethod
|
| 1270 |
+
func._fullname = info.fullname + '.' + name
|
| 1271 |
+
func.line = info.line
|
| 1272 |
+
|
| 1273 |
+
# NOTE: we would like the plugin generated node to dominate, but we still
|
| 1274 |
+
# need to keep any existing definitions so they get semantically analyzed.
|
| 1275 |
+
if name in info.names:
|
| 1276 |
+
# Get a nice unique name instead.
|
| 1277 |
+
r_name = get_unique_redefinition_name(name, info.names)
|
| 1278 |
+
info.names[r_name] = info.names[name]
|
| 1279 |
+
|
| 1280 |
+
# Add decorator for is_classmethod
|
| 1281 |
+
# The dataclasses plugin claims this is unnecessary for classmethods, but not including it results in a
|
| 1282 |
+
# signature incompatible with the superclass, which causes mypy errors to occur for every subclass of BaseModel.
|
| 1283 |
+
if is_classmethod:
|
| 1284 |
+
func.is_decorated = True
|
| 1285 |
+
v = Var(name, func.type)
|
| 1286 |
+
v.info = info
|
| 1287 |
+
v._fullname = func._fullname
|
| 1288 |
+
v.is_classmethod = True
|
| 1289 |
+
dec = Decorator(func, [NameExpr('classmethod')], v)
|
| 1290 |
+
dec.line = info.line
|
| 1291 |
+
sym = SymbolTableNode(MDEF, dec)
|
| 1292 |
+
else:
|
| 1293 |
+
sym = SymbolTableNode(MDEF, func)
|
| 1294 |
+
sym.plugin_generated = True
|
| 1295 |
+
info.names[name] = sym
|
| 1296 |
+
|
| 1297 |
+
info.defn.defs.body.append(func)
|
| 1298 |
+
|
| 1299 |
+
|
| 1300 |
+
def parse_toml(config_file: str) -> dict[str, Any] | None:
|
| 1301 |
+
"""Returns a dict of config keys to values.
|
| 1302 |
+
|
| 1303 |
+
It reads configs from toml file and returns `None` if the file is not a toml file.
|
| 1304 |
+
"""
|
| 1305 |
+
if not config_file.endswith('.toml'):
|
| 1306 |
+
return None
|
| 1307 |
+
|
| 1308 |
+
if sys.version_info >= (3, 11):
|
| 1309 |
+
import tomllib as toml_
|
| 1310 |
+
else:
|
| 1311 |
+
try:
|
| 1312 |
+
import tomli as toml_
|
| 1313 |
+
except ImportError: # pragma: no cover
|
| 1314 |
+
import warnings
|
| 1315 |
+
|
| 1316 |
+
warnings.warn('No TOML parser installed, cannot read configuration from `pyproject.toml`.')
|
| 1317 |
+
return None
|
| 1318 |
+
|
| 1319 |
+
with open(config_file, 'rb') as rf:
|
| 1320 |
+
return toml_.load(rf)
|
infer_4_37_2/lib/python3.10/site-packages/pydantic/parse.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The `parse` module is a backport module from V1."""
|
| 2 |
+
|
| 3 |
+
from ._migration import getattr_migration
|
| 4 |
+
|
| 5 |
+
__getattr__ = getattr_migration(__name__)
|
infer_4_37_2/lib/python3.10/site-packages/pydantic/validators.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The `validators` module is a backport module from V1."""
|
| 2 |
+
|
| 3 |
+
from ._migration import getattr_migration
|
| 4 |
+
|
| 5 |
+
__getattr__ = getattr_migration(__name__)
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/__main__.cpython-310.pyc
ADDED
|
Binary file (7.01 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/_cell_widths.cpython-310.pyc
ADDED
|
Binary file (7.84 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/_emoji_replace.cpython-310.pyc
ADDED
|
Binary file (1.17 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/_export_format.cpython-310.pyc
ADDED
|
Binary file (2.3 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/_fileno.cpython-310.pyc
ADDED
|
Binary file (762 Bytes). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/_inspect.cpython-310.pyc
ADDED
|
Binary file (8.6 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/_null_file.cpython-310.pyc
ADDED
|
Binary file (3.22 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/_spinners.cpython-310.pyc
ADDED
|
Binary file (12.2 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/_stack.cpython-310.pyc
ADDED
|
Binary file (812 Bytes). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/_timer.cpython-310.pyc
ADDED
|
Binary file (661 Bytes). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/_win32_console.cpython-310.pyc
ADDED
|
Binary file (18.9 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/_windows_renderer.cpython-310.pyc
ADDED
|
Binary file (1.99 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/_wrap.cpython-310.pyc
ADDED
|
Binary file (2.45 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/abc.cpython-310.pyc
ADDED
|
Binary file (1.28 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/ansi.cpython-310.pyc
ADDED
|
Binary file (5.97 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/bar.cpython-310.pyc
ADDED
|
Binary file (2.96 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/box.cpython-310.pyc
ADDED
|
Binary file (8.33 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/cells.cpython-310.pyc
ADDED
|
Binary file (4.25 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/color.cpython-310.pyc
ADDED
|
Binary file (17.7 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/color_triplet.cpython-310.pyc
ADDED
|
Binary file (1.41 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/columns.cpython-310.pyc
ADDED
|
Binary file (6.17 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/constrain.cpython-310.pyc
ADDED
|
Binary file (1.73 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/containers.cpython-310.pyc
ADDED
|
Binary file (6.47 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/emoji.cpython-310.pyc
ADDED
|
Binary file (3.21 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/file_proxy.cpython-310.pyc
ADDED
|
Binary file (2.37 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/filesize.cpython-310.pyc
ADDED
|
Binary file (2.59 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/highlighter.cpython-310.pyc
ADDED
|
Binary file (8.04 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/json.cpython-310.pyc
ADDED
|
Binary file (4.69 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/layout.cpython-310.pyc
ADDED
|
Binary file (14.6 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/markdown.cpython-310.pyc
ADDED
|
Binary file (24.9 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/measure.cpython-310.pyc
ADDED
|
Binary file (5.05 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/padding.cpython-310.pyc
ADDED
|
Binary file (4.39 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/palette.cpython-310.pyc
ADDED
|
Binary file (3.61 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/progress_bar.cpython-310.pyc
ADDED
|
Binary file (6.89 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/protocol.cpython-310.pyc
ADDED
|
Binary file (1.31 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/region.cpython-310.pyc
ADDED
|
Binary file (501 Bytes). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/repr.cpython-310.pyc
ADDED
|
Binary file (4.06 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/rule.cpython-310.pyc
ADDED
|
Binary file (3.91 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/screen.cpython-310.pyc
ADDED
|
Binary file (1.84 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/segment.cpython-310.pyc
ADDED
|
Binary file (21.2 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/spinner.cpython-310.pyc
ADDED
|
Binary file (4.39 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/rich/__pycache__/style.cpython-310.pyc
ADDED
|
Binary file (21.3 kB). View file
|
|
|