a
    y{Jh!j                  	   @  s  d Z ddlmZ ddlZddlZddlZddlmZ ddl	m
Z
 ddlmZ ddlmZmZmZmZ ddlZddlmZmZ dd	lmZ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# ddl$m%Z%m&Z&m'Z' ddl(m)Z)m*Z* ddl+m,Z,m-Z- ddl.m/Z/m0Z0 ddl1m2Z2 ddl3m4Z4m5Z5m6Z6m7Z7 ddl8m9Z9 ddl:m;Z; ej<rddl=m>Z> d
dl?m@ZA d
dl?mBZBmCZC d
dlDmEZE n
eZFeG ZAeGjHZIG dd deJZKedeAfd G d!d" d"eZLd#d$d%d&d'd(ZMd)d*d+d,d-d.ZNd)d*d/d/d0d1d2d3ZOd)d*d%d,d4d5ZPd6d*d7d)d%d8d9d:ZQddd;d6d<d7d=d>d?d=d@dAdBZRdCdDd7dEdFdGdHZSG dIdJ dJZTd>d>dKdLdMZUd>d>dKdNdOZVd*dPdQdRZWdS )Sz"Private logic for creating models.    )annotationsN)ABCMeta)partial)FunctionType)AnyCallableGenericMapping)PydanticUndefinedSchemaSerializer)dataclass_transform
deprecated   )PydanticUndefinedAnnotationPydanticUserError)create_schema_validator)GenericBeforeBaseModelWarningPydanticDeprecatedSince20   )ConfigWrapper)DecoratorInfosPydanticDescriptorProxyget_attribute_from_bases)collect_model_fieldsis_valid_field_nameis_valid_privateattr_name)GenerateSchemagenerate_pydantic_signature)PydanticGenericMetadataget_model_typevars_map)
MockValSerset_model_mocks)CallbackGetCoreSchemaHandler)get_cls_types_namespaceis_annotatedis_classvarparent_frame_namespace)ClassAttribute)ValidateCallWrapper)	Signature)Field)	FieldInfoModelPrivateAttr	BaseModelc                      s*   e Zd ZdZdddd fddZ  ZS )_ModelNamespaceDictz{A dictionary subclass that intercepts attribute setting on model classes and
    warns about overriding of decorators.
    strobjectNone)kvreturnc                   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__)selfr3   r4   existing	__class__ X/var/www/shaz/venv/lib/python3.9/site-packages/pydantic/_internal/_model_construction.pyr<   2   s    z_ModelNamespaceDict.__setitem__)__name__
__module____qualname____doc__r<   __classcell__rA   rA   r?   rB   r/   -   s   r/   T)kw_only_defaultfield_specifiersc                
      s   e Zd Zd"ddddddd	d
d fddZejs@dd	dddZed	d	ddddZd	dd fddZ	e
dddddZeededddd d!Z  ZS )#ModelMetaclassNTr0   tuple[type[Any], ...]dict[str, Any]zPydanticGenericMetadata | Nonebool
str | Noner   type)cls_namebases	namespace__pydantic_generic_metadata__#__pydantic_reset_parent_namespace___create_model_modulekwargsr5   c                   s  |r|  |\}}	}
t|||}|j|d< t||j|	|}|r|t||  durtdddd fdd}||d	< nt|d	< |	|d
< i |
||d< |jrt	|| t
 j| |||fi |}ddlm} |j}t|v r|t||k rtjtddd t|jdd |_|j|ju r"dnd	|_t||_|rB||_nt|di ddt|ddpfrrtfddD stfddD  }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 ]\}}|%|| q2|r\t&t' |_(t|d%d}t)|t*r|t+|}t,||}t-|||| t.|||d||d& t
||j/f i | |S t
 j| |||fi |S dS )'a  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_configNr.   r   r2   )r=   _ModelMetaclass__contextr5   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)r=   rX   )original_model_post_initrA   rB   wrapped_model_post_initd   s    
z7ModelMetaclass.__new__.<locals>.wrapped_model_post_initmodel_post_init__class_vars____private_attributes__r   r-   zClasses should inherit from `BaseModel` before generic classes (e.g. `typing.Generic[T]`) for pydantic generics to work properly.)
stacklevelZ__pydantic_base_init__FrS   
parametersrA   __parameters__c                 3  s   | ]}| v V  qd S NrA   .0x)r`   rA   rB   	<genexpr>       z)ModelMetaclass.__new__.<locals>.<genexpr>c                 3  s   | ]}| vr|V  qd S rb   rA   rc   )parent_parametersrA   rB   rf      rg   z, c                 S  s   g | ]}t |qS rA   )r0   rc   rA   rA   rB   
<listcomp>   rg   z*ModelMetaclass.__new__.<locals>.<listcomp>ztyping.Generic[]zJAll parameters must be present on typing.Generic; you should inherit from .c                 S  s   g | ]
}|j qS rA   )rC   rc   rA   rA   rB   ri      rg   z- Note: `typing.Generic` must go last: `class (z): ...`))originargsr`   __pydantic_parent_namespace__)raise_errorstypes_namespacecreate_model_module)0_collect_bases_datar   Z	for_modelZconfig_dictinspect_namespaceignored_typesget_model_post_initrY   frozenset_default_hash_funcr;   __new__mainr.   __mro__r   indexr9   r:   r   getattr__init__Z__pydantic_custom_init__r\   Z__pydantic_post_init__r   buildZ__pydantic_decorators__rS   r7   alltuplejoinrC   	TypeError__pydantic_complete__items__set_name__build_lenient_weakvaluedictr&   ro   r8   dictunpack_lenient_weakvaluedictr#   set_model_fieldscomplete_model_classZ__pydantic_init_subclass__)mcsrP   rQ   rR   rS   rT   rU   rV   Zbase_field_names
class_varsZbase_private_attributesconfig_wrapperprivate_attributesr[   clsr.   mroZcombined_parametersZparameters_strZgeneric_type_labelerror_messageZ	bases_strnameobjZparent_namespacerq   r?   )rZ   r`   rh   rB   ry   <   s    




$

zModelMetaclass.__new__)itemr5   c                 C  sd   | j d}|r ||v r || S |dkrXt| dd}t|trX| }|durXt| dS t|dS )zNThis is necessary to keep attribute access working for class attribute access.r^   __pydantic_core_schema____pydantic_validator__N)__dict__r7   r}   r8   r    ZrebuildAttributeError)r=   r   r   Zmaybe_mock_validatorZrebuilt_validatorrA   rA   rB   __getattr__   s    

zModelMetaclass.__getattr__zMapping[str, object])rn   rV   r5   c                 O  s   t  S rb   )r/   )r   rn   rV   rA   rA   rB   __prepare__   s    zModelMetaclass.__prepare__)instancer5   c                   s   t |dot |S )zsAvoid calling ABC _abc_subclasscheck unless we're pretty sure.

        See #3829 and python/cpython#92810
        r   )hasattrr;   __instancecheck__)r=   r   r?   rA   rB   r      s    z ModelMetaclass.__instancecheck__z6tuple[set[str], set[str], dict[str, ModelPrivateAttr]])rQ   r5   c                 C  sp   ddl m} t }t }i }| D ]D}t||r ||ur |t|di   ||j ||j q |||fS )Nr   r-   model_fields)	rz   r.   set
issubclassupdater}   keysr]   r^   )rQ   r.   field_namesr   r   baserA   rA   rB   rs      s    z"ModelMetaclass._collect_bases_dataEThe `__fields__` attribute is deprecated, use `model_fields` instead.)categorydict[str, FieldInfo]r5   c                 C  s   t dt | jS )Nr   )r9   r:   DeprecationWarningr   r=   rA   rA   rB   
__fields__   s    zModelMetaclass.__fields__)NTN)rC   rD   rE   ry   typingTYPE_CHECKINGr   classmethodr   r   staticmethodrs   propertyr   r   r   rG   rA   rA   r?   rB   rJ   :   s"      " rJ   r.   r   r2   )r=   	__contextr5   c                 C  sP   t | dddu rLi }| j D ] \}}| }|tur|||< qt| d| 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.
    Z__pydantic_private__N)r}   r^   r   get_defaultr
   object_setattr)r=   r   Zpydantic_privater   private_attrdefaultrA   rA   rB   rY      s    	
rY   rL   rK   zCallable[..., Any] | None)rR   rQ   r5   c                 C  s8   d| v r| d S ddl m} t|d}||jur4|S dS )zaGet the `model_post_init` method from the namespace or the class bases, or `None` if not defined.r\   r   r-   N)rz   r.   r   r\   )rR   rQ   r.   r\   rA   rA   rB   rv     s    

rv   zset[str]zdict[str, ModelPrivateAttr])rR   ru   base_class_varsbase_class_fieldsr5   c              	     s  ddl m}m m} |t  }i }| di }d|v s>d| v rFtdt }	t| 	 D ]\}
}|
dkrnqXqXt
|tr|j| d kr|j| d rqXqXt
||s|jjd	kr|	|
 qXqXt
| r|
d
rtd|
dn$t|
r
tdd|
 d|
d|||
< | |
= qXt
||rXt|
sX|
dp>d}td|d|
dqX|
d
rhqXqXt|
r|
|vst||
 s||d||
< | |
= qX|
|v rqXqX|
|vrX|
|v rtd|
dddqXt
||rtd|
dddqXtd|
 d|d|
 dddqX|	 D ]\}}t|r"||vr"||	vr"t|s"||vr"t|ddd	kr"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   )r+   r,   PrivateAttr__annotations__Z__root__zUTo define root models, use `pydantic.RootModel` rather than a field called '__root__'rW   rD   rE   	functools__zXPrivate attributes must not use dunder names; use a single underscore prefix instead of rk   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']`.Nc                 3  s   | ]}t | r|V  qd S rb   )r8   )rd   r4   r,   rA   rB   rf     rg   z$inspect_namespace.<locals>.<genexpr>)fieldsr+   r,   r   default_ignored_typesr7   r   r   listr   r8   rO   rD   rE   
startswithr@   add	NameErrorr   lstripr   r%   r   r}   r$   typing_extensionsget_argsnext)rR   ru   r   r   r+   r   Zall_ignored_typesr   Zraw_annotationsignored_namesvar_namevalueZsuggested_nameZann_nameZann_typer   metadatar   rA   r   rB   rt     s    









rt   c                 C  s@   d| v rd S t |d}|d tjhv r<ddddd}|| d< d S )N__hash__r   int)r=   r5   c                 S  s   t | jt t| j  S rb   )hashr@   r   r   valuesr   rA   rA   rB   	hash_func  s    z(set_default_hash_func.<locals>.hash_func)r   r1   r   )rR   rQ   Zbase_hash_funcr   rA   rA   rB   rx     s    
rx   ztype[BaseModel]r   )r   rQ   r   rq   r5   c           	      C  sl   t | }t| ||||d\}}|| _| j| |D ]2}| j|d}|dur4|jtur4t	| ||j q4dS )a.  Collect and set `cls.model_fields` and `cls.__class_vars__`.

    Args:
        cls: BaseModel or dataclass.
        bases: Parents of the class, generally `cls.__bases__`.
        config_wrapper: The config wrapper instance.
        types_namespace: Optional extra namespace to look for types in.
    )typevars_mapN)
r   r   r   r]   r   r^   popr   r
   setattr)	r   rQ   r   rq   r   r   r   r3   r   rA   rA   rB   r     s    r   )rp   rr   r0   rM   zdict[str, Any] | NonerN   )r   rP   r   rp   rq   rr   r5   c             
   C  s*  t | }t|||}tt|jdd|dd}|jr@t| | dS z| | |}	W nB ty }
 z*|rf t| |d|
j	 d W Y d}
~
dS d}
~
0 0 |
| }z||	}	W n  |jy   t| | Y dS 0 |	| _t|	| |p| j| j|rdnd||j| _t|	|| _d	| _td
t| j| j|| _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.
        cls_name: The model or dataclass name.
        config_wrapper: The config wrapper instance.
        raise_errors: Whether to raise errors.
        types_namespace: Optional extra namespace to look for types in.
        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`.
    F)Zfrom_dunder_get_core_schemaunpack)Zref_moder6   NZcreate_modelr.   T__signature__)r   r   r"   r   Zgenerate_schemaZdefer_buildr!   Z__get_pydantic_core_schema__r   r   core_configZclean_schemaZCollectedInvalidr   r   rD   rE   Zplugin_settingsr   r   Z__pydantic_serializer__r   r'   generate_model_signaturer~   r   r   )r   rP   r   rp   rq   rr   r   Z
gen_schemahandlerZschemaer   rA   rA   rB   r     sV    



	r   zCallable[..., None]r   r)   )initr   r   r5   c                 C  s   t | ||S )zGenerate signature for model based on its fields.

    Args:
        init: The class init.
        fields: The model fields.
        config_wrapper: The config wrapper instance.

    Returns:
        The model signature.
    )r   )r   r   r   rA   rA   rB   r     s    r   c                   @  s:   e Zd ZdZddddZddddZd	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 | _ nt|| _ d S rb   )_wrweakrefref)r=   r   rA   rA   rB   r~   1  s    z_PydanticWeakRef.__init__r   c                 C  s   | j d u rd S |   S d S rb   )r   r   rA   rA   rB   __call__9  s    
z_PydanticWeakRef.__call__z4tuple[Callable, tuple[weakref.ReferenceType | None]]c                 C  s   t |  ffS rb   )r   r   rA   rA   rB   
__reduce__?  s    z_PydanticWeakRef.__reduce__N)rC   rD   rE   rF   r~   r   r   rA   rA   rA   rB   r      s   r   )dr5   c              	   C  sR   | du rdS i }|   D ]4\}}zt|}W n tyB   |}Y n0 |||< 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   )r   resultr3   r4   proxyrA   rA   rB   r   C  s    

r   c                 C  sP   | du rdS i }|   D ]2\}}t|trB| }|durJ|||< q|||< q|S )zAInverts the transform performed by `build_lenient_weakvaluedict`.N)r   r8   r   )r   r   r3   r4   rA   rA   rB   r   W  s    


r   r   c                  C  s   ddl m}  ttttt| tfS )Nr   ComputedFieldInfo)r   r   r   r   r   r   r   r(   r   rA   rA   rB   r   g  s    r   )XrF   
__future__r   Z_annotationsr   r9   r   abcr   r   r   typesr   r   r   r   r	   r   Zpydantic_corer
   r   r   r   errorsr   r   Zplugin._schema_validatorr   r   r   _configr   Z_decoratorsr   r   r   _fieldsr   r   r   Z_generate_schemar   r   Z	_genericsr   r   Z_mock_val_serr    r!   Z_schema_generation_sharedr"   Z_typing_extrar#   r$   r%   r&   Z_utilsr'   Z_validate_callr(   r   inspectr)   r   r*   ZPydanticModelFieldr+   r,   rz   r.   r   r1   __setattr__r   r   r/   rJ   rY   rv   rt   rx   r   r   r   r   r   r   r   rA   rA   rA   rB   <module>   sb    Bu#T#