o
    Zh                     @  s  d Z ddlmZ ddlZddlZddlZddlZddlZddl	Z	ddl
mZ ddlmZmZmZ ddlmZ ddlmZmZmZmZmZmZ ddlmZmZ dd	lmZmZmZmZm Z  dd
l!m"Z" ddl#m$Z$m%Z% ddl&m'Z' ddlm(Z(m)Z) ddl*m+Z+ ddl,m-Z-m.Z.m/Z/m0Z0 ddl1m2Z2m3Z3m4Z4 ddl5m6Z6m7Z7 ddl8m9Z9m:Z: ddl;m<Z<m=Z= ddl>m?Z? ddl@mAZA ddlBmCZC ddlDmEZEmFZFmGZGmHZH ddlImJZJmKZK ejLrddlMmNZO ddlMmPZPmQZQ ddlMmRZS ddlTmUZU ne)ZVeW ZOeW ZSeWjXZYG dd  d eZZ[d!d"dbd'd(Z\ed)eOeSe\fd*G d+d, d,eZ]dcd1d2Z^ddd8d9Z_ded?d@Z`dfdCdDZadgdEdFZbdhdKdLZcd)dddMdidRdSZddjdTdUZeG dVdW dWZfG dXdY dYZgdkd\d]Zhdkd^d_Ziedld`daZjdS )mz"Private logic for creating models.    )annotationsN)ABCMeta)cachepartialwraps)FunctionType)AnyCallableGenericLiteralNoReturncast)PydanticUndefinedSchemaSerializer)TypeAliasTypedataclass_transform
deprecatedget_args
get_origin)typing_objects   )PydanticUndefinedAnnotationPydanticUserError)create_schema_validator)GenericBeforeBaseModelWarningPydanticDeprecatedSince20   )ConfigWrapper)DecoratorInfosPydanticDescriptorProxyget_attribute_from_basesunwrap_wrapped_function)collect_model_fieldsis_valid_field_nameis_valid_privateattr_name)GenerateSchemaInvalidSchemaError)PydanticGenericMetadataget_model_typevars_map)import_cached_base_modelimport_cached_field_info)set_model_mocks)
NsResolver)generate_pydantic_signature)_make_forward_refeval_type_backportis_classvar_annotationparent_frame_namespace)LazyClassAttributeSafeGetItemProxy)Field)	FieldInfoModelPrivateAttr)PrivateAttr)	BaseModelc                      s"   e Zd ZdZd
 fdd	Z  ZS )_ModelNamespaceDictz{A dictionary subclass that intercepts attribute setting on model classes and
    warns about overriding of decorators.
    kstrvobjectreturnNonec                   sL   |  |d }|r||urt|trtd| d|jj d t ||S )N`z"` overrides an existing Pydantic `z` decorator)	get
isinstancer   warningswarnZdecorator_infoZdecorator_reprsuper__setitem__)selfr:   r<   existing	__class__ ]/var/www/html/lang_env/lib/python3.10/site-packages/pydantic/_internal/_model_construction.pyrF   <   s   z_ModelNamespaceDict.__setitem__)r:   r;   r<   r=   r>   r?   )__name__
__module____qualname____doc__rF   __classcell__rK   rK   rI   rL   r9   7   s    r9   FinitrS   Literal[False]r>   r   c                 C     dS )zOnly for typing purposes. Used as default value of `__pydantic_fields_set__`,
    `__pydantic_extra__`, `__pydantic_private__`, so they could be ignored when
    synthesizing the `__init__` signature.
    NrK   rR   rK   rK   rL   NoInitFieldD       rV   T)kw_only_defaultfield_specifiersc                      s   e Zd Z			d0d1 fddZejsd2ddZed3ddZd4 fddZ	d5 fd!d"Z
ed6d$d%Zeed&dd'd7d)d*Zed8d+d,Zd9 fd.d/Z  ZS ):ModelMetaclassNTcls_namer;   basestuple[type[Any], ...]	namespacedict[str, Any]__pydantic_generic_metadata__PydanticGenericMetadata | None#__pydantic_reset_parent_namespace__bool_create_model_module
str | Nonekwargsr   r>   typec                   s  |r|  |\}}	}
t|||}|j|d< t||j|	|}|s#|
r@t||  dur<t d6 fd	d
}||d< nt|d< |	|d< i |
||d< t	dt
 j| |||fi |}t }|j}t|v ry|t||k rytjtddd t|jdd |_|j|ju rdnd|_i |_t||_|r||_nt|di ddt|ddpr3r3tfddD s3ddlm } t!fddD }|v r|vrd"dd |D }|j# d| d |j# d!| d"}t$|| }d"d#d |D }d$| d%}d&| d'}t|vr/d"d(d |D |g }|d)|j# d*| d+7 }t$|ddd,|_d|_%|& D ]\}}|'|| qA|rVt(t) |_*t|d-d}t+|t,rft-|}t.|d.}t/|||d/ d0d1 |jj0& D |_1|j2rt3| n	t4||d||d2 |j5rd3|vrt6|| t
||j7di | |S d4D ]	}|8|d q|d5i 9  t
 j| |||fi |S )7a  Metaclass for creating Pydantic models.

        Args:
            cls_name: The name of the class to be created.
            bases: The base classes of the class to be created.
            namespace: The attribute dictionary of the class to be created.
            __pydantic_generic_metadata__: Metadata for generic models.
            __pydantic_reset_parent_namespace__: Reset parent namespace.
            _create_model_module: The module of the class to be created, if created by `create_model`.
            **kwargs: Catch-all for any other keyword arguments.

        Returns:
            The new class created by the metaclass.
        model_configNrG   r8   contextr   r>   r?   c                  s   t | |  | | dS )zWe need to both initialize private attributes and call the user-defined model_post_init
                        method.
                        N)init_private_attributes)rG   ri   )original_model_post_initrK   rL   wrapped_model_post_initx   s   
z7ModelMetaclass.__new__.<locals>.wrapped_model_post_initmodel_post_init__class_vars____private_attributes__type[BaseModel]zClasses should inherit from `BaseModel` before generic classes (e.g. `typing.Generic[T]`) for pydantic generics to work properly.r   
stacklevelZ__pydantic_base_init__Fr`   
parametersrK   __parameters__c                 3  s    | ]}| v V  qd S NrK   .0x)rs   rK   rL   	<genexpr>   s    z)ModelMetaclass.__new__.<locals>.<genexpr>)RootModelRootTypec                 3  s    | ]	}| vr|V  qd S ru   rK   rv   )parent_parametersrK   rL   ry      s    z, c                 S     g | ]}|j qS rK   rM   rv   rK   rK   rL   
<listcomp>       z*ModelMetaclass.__new__.<locals>.<listcomp>zS is a subclass of `RootModel`, but does not include the generic type identifier(s) zL in its parameters. You should parametrize RootModel directly, e.g., `class z(RootModel[z	]): ...`.c                 S  s   g | ]}t |qS rK   )r;   rv   rK   rK   rL   r~      s    ztyping.Generic[]zJAll parameters must be present on typing.Generic; you should inherit from .c                 S  r|   rK   r}   rv   rK   rK   rL   r~      r   z- Note: `typing.Generic` must go last: `class (z): ...`))originargsrs   __pydantic_parent_namespace__)parent_namespace)config_wrapperns_resolverc                 S     i | ]\}}||j qS rK   inforw   r:   r<   rK   rK   rL   
<dictcomp>   s    z*ModelMetaclass.__new__.<locals>.<dictcomp>raise_errorsr   create_model_module__hash__)Z__pydantic_fields_set____pydantic_extra____pydantic_private____annotations__rG   r8   ri   r   r>   r?   ):_collect_bases_datar   Z	for_modelZconfig_dictinspect_namespaceignored_typesget_model_post_initr   rj   r   rE   __new__r)   __mro__r
   indexrC   rD   r   getattr__init__Z__pydantic_custom_init__rm   Z__pydantic_post_init__Z__pydantic_setattr_handlers__r   build__pydantic_decorators__r`   rA   allZ
root_modelrz   tuplejoinrM   	TypeError__pydantic_complete__items__set_name__build_lenient_weakvaluedictr1   r   rB   dictunpack_lenient_weakvaluedictr,   set_model_fieldscomputed_fields__pydantic_computed_fields__Zdefer_buildr+   complete_model_classfrozenset_default_hash_funcZ__pydantic_init_subclass__popclear)mcsr[   r\   r^   r`   rb   rd   rf   Zbase_field_names
class_varsZbase_private_attributesr   private_attributesrl   clsZ
BaseModel_mrorz   Zmissing_parametersZparameters_strerror_messageZcombined_parametersZgeneric_type_labelZ	bases_strnameobjr   r   Zinstance_slotrI   )rk   rs   r{   rL   r   P   s   



 $




zModelMetaclass.__new__itemc                 C  s(   | j d}|r||v r|| S t|)zNThis is necessary to keep attribute access working for class attribute access.ro   )__dict__rA   AttributeError)rG   r   r   rK   rK   rL   __getattr__
  s   zModelMetaclass.__getattr__r   dict[str, object]c                 O  s   t  S ru   )r9   )r   r   rf   rK   rK   rL   __prepare__  s   zModelMetaclass.__prepare__instancec                      t |do
t |S )zsAvoid calling ABC _abc_instancecheck unless we're pretty sure.

        See #3829 and python/cpython#92810
        r   )hasattrrE   __instancecheck__)rG   r   rI   rK   rL   r        z ModelMetaclass.__instancecheck__subclass	type[Any]c                   r   )zsAvoid calling ABC _abc_subclasscheck unless we're pretty sure.

        See #3829 and python/cpython#92810
        r   )r   rE   __subclasscheck__)rG   r   rI   rK   rL   r     r   z ModelMetaclass.__subclasscheck__6tuple[set[str], set[str], dict[str, ModelPrivateAttr]]c                 C  sj   t  }t }t }i }| D ]"}t||r/||ur/|t|di   ||j ||j q|||fS )N__pydantic_fields__)r)   set
issubclassupdater   keysrn   ro   )r\   r8   field_namesr   r   baserK   rK   rL   r   #  s   
z"ModelMetaclass._collect_bases_dataEThe `__fields__` attribute is deprecated, use `model_fields` instead.)categorydict[str, FieldInfo]c                 C  s   t jdtdd t| di S )Nr   r   rq   r   )rC   rD   r   r   rG   rK   rK   rL   
__fields__2  s   zModelMetaclass.__fields__c                 C  s0   t | dsdS td| j}tdd | D S )zWhether the fields where successfully collected (i.e. type hints were successfully resolves).

        This is a private attribute, not meant to be used outside Pydantic.
        r   Fr   c                 s  s    | ]}|j V  qd S ru   )Z	_complete)rw   
field_inforK   rK   rL   ry   G  s    z>ModelMetaclass.__pydantic_fields_complete__.<locals>.<genexpr>)r   r   r   r   values)rG   Zfield_infosrK   rK   rL   __pydantic_fields_complete__<  s   
z+ModelMetaclass.__pydantic_fields_complete__	list[str]c                   s$   t t  }d|v r|d |S )Nr   )listrE   __dir__remove)rG   
attributesrI   rK   rL   r   I  s   
zModelMetaclass.__dir__)NTN)r[   r;   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   rf   r   r>   rg   )r   r;   r>   r   )r   r   rf   r   r>   r   )r   r   r>   rc   )r   r   r>   rc   )r\   r]   r>   r   )r>   r   )r>   rc   )r>   r   )rM   rN   rO   r   typingTYPE_CHECKINGr   classmethodr   r   r   staticmethodr   propertyr   r   r   r   rQ   rK   rK   rI   rL   rZ   N   s(     8

rZ   rG   r8   ri   r?   c                C  sT   t | dddu r(i }| j D ]\}}| }|tur|||< qt| d| dS dS )a  This function is meant to behave like a BaseModel method to initialise private attributes.

    It takes context as an argument since that's what pydantic-core passes when calling it.

    Args:
        self: The BaseModel instance.
        context: The context.
    r   N)r   ro   r   get_defaultr   object_setattr)rG   ri   Zpydantic_privater   private_attrdefaultrK   rK   rL   rj   P  s   	rj   r^   r_   r\   r]   Callable[..., Any] | Nonec                 C  s2   d| v r| d S t  }t|d}||jur|S dS )zaGet the `model_post_init` method from the namespace or the class bases, or `None` if not defined.rm   N)r)   r    rm   )r^   r\   r8   rm   rK   rK   rL   r   b  s   

r   r   base_class_varsset[str]base_class_fieldsdict[str, ModelPrivateAttr]c              
     s  ddl m m} t }|t  }i }| di }d|v s d| v r$tdt }	t| 	 D ]\}
}|
dks9|
dkr:q-t
|trS|j| d krSd	| v rS|j| d	 rSq-t
||s^|jjd
krd|	|
 q-t
| r|
drvtd|
dt|
rtdd|
 d|
d|||
< | |
= q-t
||rt|
s|
dpd}td|d|
d|
drq-t|
r|
|vst||
 st ||d||
< | |
= q-|
|v rq-|
|vr|
|v rtd|
dddt
||rtd|
dddtd|
 d|d|
 dddq-|	 D ]~\}}t|r||vr||	vrt|s||vrt|ddd
krt
|tr[td}|dur[ztt|dd d!|j|jd"}W n ttfyZ   Y nw t !t"|rt#|^}}t$ fd#d$|D d}|dur|||< q| ||< q|S )%a  Iterate over the namespace and:
    * gather private attributes
    * check for items which look like fields but are not (e.g. have no annotation) and warn.

    Args:
        namespace: The attribute dictionary of the class to be created.
        ignored_types: A tuple of ignore types.
        base_class_vars: A set of base class class variables.
        base_class_fields: A set of base class fields.

    Returns:
        A dict contains private attributes info.

    Raises:
        TypeError: If there is a `__root__` field in model.
        NameError: If private attribute name is invalid.
        PydanticUserError:
            - If a field does not have a type annotation.
            - If a field on base class was overridden by a non-annotated attribute.
    r   )r6   r7   r   Z__root__zUTo define root models, use `pydantic.RootModel` rather than a field called '__root__'rh   r   rN   rO   	functools__zXPrivate attributes must not use dunder names; use a single underscore prefix instead of r   zJPrivate attributes must not use valid field names; use sunder names, e.g. _z instead of Zmy_fieldz>Fields must not use names with leading underscores; e.g., use )r   zField z defined on a base class was overridden by a non-annotated attribute. All field definitions, including overrides, require a type annotation.zmodel-field-overridden)codez requires a type annotationzmodel-field-missing-annotationz)A non-annotated attribute was detected: `z = z3`. All model fields require a type annotation; if `z` is not meant to be a field, you may be able to resolve this error by annotating it as a `ClassVar` or updating `model_config['ignored_types']`.NFT)is_argumentis_class)globalnslocalnsc                 3  s    | ]
}t | r|V  qd S ru   )rB   )rw   r<   r6   rK   rL   ry     s    z$inspect_namespace.<locals>.<genexpr>)%fieldsr6   r7   r*   default_ignored_typesrA   r   r   r   r   rB   rg   rN   rO   
startswithrJ   add	NameErrorr#   lstripr$   r0   r   r   r   r;   sys	_getframer/   r.   	f_globalsf_localsr   Zis_annotatedr   r   next)r^   r   r   r   r7   r5   Zall_ignored_typesr   Zraw_annotationsignored_namesvar_namevalueZsuggested_nameZann_nameZann_typeframer   metadatar   rK   r   rL   r   n  s   















r   r   rp   c                 C  s@   t |d}t| }|d tjhv st|dd |jkr|| _d S d S )Nr   __code__)r    make_hash_funcr=   r   r   r  )r   r\   Zbase_hash_funcZnew_hash_funcrK   rK   rL   r     s
   
 
r   c                   s0   | j rtj| j   ndd  d	 fdd}|S )
Nc                 S  rU   )Nr   rK   )r   rK   rK   rL   <lambda>  rW   z make_hash_func.<locals>.<lambda>rG   r   r>   intc                   s6   zt  | jW S  ty   t  t| j Y S w ru   )hashr   KeyErrorr3   r   getterrK   rL   	hash_func  s
   z!make_hash_func.<locals>.hash_func)rG   r   r>   r  )r   operator
itemgetterr   )r   r  rK   r  rL   r    s   
r  r   r   r   NsResolver | Nonec                 C  sj   t | }t| |||d\}}|| _| j| |D ]}| j|d}|dur2|jtur2t	| ||j qdS )zCollect and set `cls.__pydantic_fields__` and `cls.__class_vars__`.

    Args:
        cls: BaseModel or dataclass.
        config_wrapper: The config wrapper instance.
        ns_resolver: Namespace resolver to use when getting model annotations.
    )typevars_mapN)
r(   r"   r   rn   r   ro   r   r   r   setattr)r   r   r   r  r   r   r:   r  rK   rK   rL   r     s   r   r   r   rc   r   re   c          
   
   C  s$  t | }t|||}z|| }W n  ty1 } z|r t| d|j d W Y d}~dS d}~ww |j| jd}	z||}W n t	yN   t|  Y dS w dd | j
j D | _t|  || _t|| |pi| j| j|rodnd|	|j| _t||	| _d	| _td
tt| j| j|j|jd| _d	S )a  Finish building a model class.

    This logic must be called after class has been created since validation functions must be bound
    and `get_type_hints` requires a class object.

    Args:
        cls: BaseModel or dataclass.
        config_wrapper: The config wrapper instance.
        raise_errors: Whether to raise errors.
        ns_resolver: The namespace resolver instance to use during schema building.
        create_model_module: The module of the class to be created, if created by `create_model`.

    Returns:
        `True` if the model is successfully completed, else `False`.

    Raises:
        PydanticUndefinedAnnotation: If `PydanticUndefinedAnnotation` occurs in`__get_pydantic_core_schema__`
            and `raise_errors=True`.
    r@   NF)titlec                 S  r   rK   r   r   rK   rK   rL   r   f  s    z(complete_model_class.<locals>.<dictcomp>Zcreate_modelr8   T__signature__)rS   r   validate_by_nameextra) r(   r%   Zgenerate_schemar   r+   r   core_configrM   Zclean_schemar&   r   r   r   r   set_deprecated_descriptorsZ__pydantic_core_schema__r   rN   rO   Zplugin_settingsZ__pydantic_validator__r   Z__pydantic_serializer__r   r2   r   r-   r   r   r  r  r  )
r   r   r   r   r   r  Z
gen_schemaZschemaer  rK   rK   rL   r   2  s^   
	
r   c                 C  s   | j  D ]\}}|j }dur t|}|| | t| || q| j D ]%\}}|j }durKtt|j	dsKt||j	}|| | t| || q&dS )z8Set data descriptors on the class for deprecated fields.N__deprecated__)
r   r   Zdeprecation_message_DeprecatedFieldDescriptorr   r  r   r   r!   wrapped_property)r   fieldr   msgZdescZcomputed_field_inforK   rK   rL   r    s   r  c                   @  sF   e Zd ZU dZded< ddd
dZdddZddddZd ddZdS )!r  aW  Read-only data descriptor used to emit a runtime deprecation warning before accessing a deprecated field.

    Attributes:
        msg: The deprecation message to be emitted.
        wrapped_property: The property instance if the deprecated field is a computed field, or `None`.
        field_name: The name of the field being deprecated.
    r;   
field_nameNr  r  property | Noner>   r?   c                 C  s   || _ || _d S ru   )r  r  )rG   r  r  rK   rK   rL   r     s   
z#_DeprecatedFieldDescriptor.__init__r   rp   r   c                 C  s
   || _ d S ru   )r  )rG   r   r   rK   rK   rL   r        
z'_DeprecatedFieldDescriptor.__set_name__r   BaseModel | Noneobj_typetype[BaseModel] | Noner   c                 C  sb   |d u r| j d ur| j d |S t| jtj| jtjdd | j d ur+| j ||S |j	| j S )Nr   rq   )
r  __get__r   r  rC   rD   r  builtinsDeprecationWarningr   )rG   r   r#  rK   rK   rL   r%    s   


z"_DeprecatedFieldDescriptor.__get__r  r   c                 C  s
   t | jru   )r   r  )rG   r   r  rK   rK   rL   __set__  r!  z"_DeprecatedFieldDescriptor.__set__ru   )r  r;   r  r   r>   r?   )r   rp   r   r;   r>   r?   )r   r"  r#  r$  r>   r   )r   r   r  r   r>   r   )	rM   rN   rO   rP   r   r   r   r%  r(  rK   rK   rK   rL   r    s   
 
r  c                   @  s.   e Zd ZdZdddZdddZdd
dZdS )_PydanticWeakRefa  Wrapper for `weakref.ref` that enables `pickle` serialization.

    Cloudpickle fails to serialize `weakref.ref` objects due to an arcane error related
    to abstract base classes (`abc.ABC`). This class works around the issue by wrapping
    `weakref.ref` instead of subclassing it.

    See https://github.com/pydantic/pydantic/issues/6763 for context.

    Semantics:
        - If not pickled, behaves the same as a `weakref.ref`.
        - If pickled along with the referenced object, the same `weakref.ref` behavior
          will be maintained between them after unpickling.
        - If pickled without the referenced object, after unpickling the underlying
          reference will be cleared (`__call__` will always return `None`).
    r   r   c                 C  s"   |d u r	d | _ d S t|| _ d S ru   )_wrweakrefref)rG   r   rK   rK   rL   r     s   
z_PydanticWeakRef.__init__r>   c                 C  s   | j d u rd S |   S ru   )r*  r   rK   rK   rL   __call__  s   
z_PydanticWeakRef.__call__4tuple[Callable, tuple[weakref.ReferenceType | None]]c                 C  s   t |  ffS ru   )r)  r   rK   rK   rL   
__reduce__  s   z_PydanticWeakRef.__reduce__N)r   r   )r>   r   )r>   r.  )rM   rN   rO   rP   r   r-  r/  rK   rK   rK   rL   r)    s
    

r)  ddict[str, Any] | Nonec              	   C  sR   | du rdS i }|   D ]\}}zt|}W n ty!   |}Y nw |||< q|S )aX  Takes an input dictionary, and produces a new value that (invertibly) replaces the values with weakrefs.

    We can't just use a WeakValueDictionary because many types (including int, str, etc.) can't be stored as values
    in a WeakValueDictionary.

    The `unpack_lenient_weakvaluedict` function can be used to reverse this operation.
    N)r   r)  r   )r0  resultr:   r<   proxyrK   rK   rL   r     s   
r   c                 C  sP   | du rdS i }|   D ]\}}t|tr!| }|dur |||< q|||< q|S )zAInverts the transform performed by `build_lenient_weakvaluedict`.N)r   rB   r)  )r0  r2  r:   r<   rK   rK   rL   r     s   

r   c                  C  s<   ddl m}  ttttt| tg}tj	dkr|
tj t|S )Nr   )ComputedFieldInfo)      )r   r4  r   r   r   r   r   r   r   version_infoappendr   r   )r4  r   rK   rK   rL   r     s   

r   )rS   rT   r>   r   r   )r^   r_   r\   r]   r>   r   )
r^   r_   r   r]   r   r   r   r   r>   r   )r   rp   r\   r]   r>   r?   )r   rp   r>   r   )r   rp   r   r   r   r  r>   r?   )r   rp   r   r   r   rc   r   r  r   re   r>   rc   )r   rp   r>   r?   )r0  r1  r>   r1  )r>   r]   )krP   
__future__r   Z_annotationsr&  r  r   r   rC   r+  abcr   r   r   r   r   typesr   r   r	   r
   r   r   r   Zpydantic_corer   r   typing_extensionsr   r   r   r   r   Ztyping_inspectionr   errorsr   r   Zplugin._schema_validatorr   r   r   _configr   Z_decoratorsr   r   r    r!   _fieldsr"   r#   r$   Z_generate_schemar%   r&   Z	_genericsr'   r(   Z_import_utilsr)   r*   Z_mock_val_serr+   Z_namespace_utilsr,   
_signaturer-   Z_typing_extrar.   r/   r0   r1   Z_utilsr2   r3   r   r   r4   ZPydanticModelFieldr5   r6   r7   ZPydanticModelPrivateAttrmainr8   r'  r=   __setattr__r   r   r9   rV   rZ   rj   r   r   r   r  r   r   r  r  r)  r   r   r   rK   rK   rK   rL   <module>   s~     
  


 
	

#
V%
#
