o
    pfm                     @  sT  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m	Z	 ddl
mZ ddlmZ ddl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) ddl*m+Z+m,Z, ddl-m.Z.m/Z/ ddl0m1Z1 ddl2m3Z3 ddl4m5Z5m6Z6m7Z7m8Z8 ddl9m:Z:m;Z; ddl<m=Z= ej>rd
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	ZLdWd)d*ZMdXd0d1ZNdYd7d8ZOdZd;d<ZPd[d=d>ZQd\dBdCZRdddDd]dLdMZSG dNdO dOZTd^dQdRZUd^dSdTZVd_dUdVZWdS )`z"Private logic for creating models.    )annotationsN)ABCMeta)partial)FunctionType)AnyCallableGeneric)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)PydanticGenericMetadataget_model_typevars_map)
MockValSerset_model_mocks)CallbackGetCoreSchemaHandler)generate_pydantic_signature)get_cls_types_namespaceis_annotatedis_classvarparent_frame_namespace)ClassAttributeSafeGetItemProxy)ValidateCallWrapper)Field)	FieldInfoModelPrivateAttr	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warndecorator_infodecorator_reprsuper__setitem__)selfr/   r1   existing	__class__ _/home/ertert/spirit/venv/lib/python3.10/site-packages/pydantic/_internal/_model_construction.pyr=   2   s   z_ModelNamespaceDict.__setitem__)r/   r0   r1   r2   r3   r4   )__name__
__module____qualname____doc__r=   __classcell__rB   rB   r@   rC   r.   -   s    r.   T)kw_only_defaultfield_specifiersc                      s   e Zd Z			d*d+ fddZejsd,ddZed-ddZd. fddZ	e
d/d d!Zeed"dd#d0d%d&Zd1 fd(d)Z  ZS )2ModelMetaclassNTcls_namer0   basestuple[type[Any], ...]	namespacedict[str, Any]__pydantic_generic_metadata__PydanticGenericMetadata | None#__pydantic_reset_parent_namespace__bool_create_model_module
str | Nonekwargsr   r3   typec                   s  |rh|  |\}}	}
t|||}|j|d< t||j|	|}|r:t||  dur6d, fd	d
}||d< nt|d< |	|d< i |
||d< t j	| |||fi |}ddl
m} |j}t|v rs|t||k rstjtddd t|jdd |_|j|ju rdnd|_t||_|r||_nlt|di ddt|ddprrtfddD stfddD  }ddd |D }d| d}d | d!}t|vrdd"d |D |g }|d#|j d$| d%7 }t |ddd&|_d|_!|" D ]\}}|#|| q|rt$t% |_&t|d'd}t'|t(r+t)|}t*||}t+|||| |j,rEd(|vrEt-|| t.|||d||d) d*d+ |jj/" D |_0t||j1di | |S t j	| |||fi |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-   _ModelMetaclass__contextr   r3   r4   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>   rZ   )original_model_post_initrB   rC   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.)
stacklevel__pydantic_base_init__FrQ   
parametersrB   __parameters__c                 3  s    | ]}| v V  qd S NrB   .0x)rc   rB   rC   	<genexpr>   s    z)ModelMetaclass.__new__.<locals>.<genexpr>c                 3  s    | ]	}| vr|V  qd S re   rB   rf   )parent_parametersrB   rC   ri      s    z, c                 S  s   g | ]}t |qS rB   )r0   rf   rB   rB   rC   
<listcomp>   s    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 rB   )rD   rf   rB   rB   rC   rk      s    z- Note: `typing.Generic` must go last: `class (z): ...`))originargsrc   __pydantic_parent_namespace____hash__)raise_errorstypes_namespacecreate_model_modulec                 S  s   i | ]\}}||j qS rB   )info)rg   r/   r1   rB   rB   rC   
<dictcomp>   s    z*ModelMetaclass.__new__.<locals>.<dictcomp>)r>   r-   rZ   r   r3   r4   )2_collect_bases_datar   	for_modelconfig_dictinspect_namespaceignored_typesget_model_post_initr[   r<   __new__mainr-   __mro__r   indexr8   r9   r   getattr__init____pydantic_custom_init__r^   __pydantic_post_init__r   build__pydantic_decorators__rQ   r6   alltuplejoinrD   	TypeError__pydantic_complete__items__set_name__build_lenient_weakvaluedictr%   rq   r7   dictunpack_lenient_weakvaluedictr"   set_model_fieldsfrozenset_default_hash_funccomplete_model_classcomputed_fieldsmodel_computed_fields__pydantic_init_subclass__)mcsrL   rM   rO   rQ   rS   rU   rW   base_field_names
class_varsbase_private_attributesconfig_wrapperprivate_attributesr]   clsr-   mrocombined_parametersparameters_strgeneric_type_labelerror_message	bases_strnameobjparent_namespacert   r@   )r\   rc   rj   rC   r~   <   s   





zModelMetaclass.__new__itemc                 C  s`   | j d}|r||v r|| S |dkr,t| dd}t|tr,| }|dur,t| dS t|)zNThis is necessary to keep attribute access working for class attribute access.r`   __pydantic_core_schema____pydantic_validator__N)__dict__r6   r   r7   r   rebuildAttributeError)r>   r   r   maybe_mock_validatorrebuilt_validatorrB   rB   rC   __getattr__   s   

zModelMetaclass.__getattr__rp   dict[str, object]c                 O  s   t  S re   )r.   )r   rp   rW   rB   rB   rC   __prepare__   s   zModelMetaclass.__prepare__instancec                   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@   rB   rC   r      s   z ModelMetaclass.__instancecheck__6tuple[set[str], set[str], dict[str, ModelPrivateAttr]]c                 C  sp   ddl m} t }t }i }| D ]"}t||r2||ur2|t|di   ||j ||j q|||fS )Nr   r,   model_fields)	r   r-   set
issubclassupdater   keysr_   r`   )rM   r-   field_namesr   r   baserB   rB   rC   rx      s   
z"ModelMetaclass._collect_bases_dataEThe `__fields__` attribute is deprecated, use `model_fields` instead.)categorydict[str, FieldInfo]c                 C  s   t dt | jS )Nr   )r8   r9   r   r   r>   rB   rB   rC   
__fields__   s   zModelMetaclass.__fields__	list[str]c                   s$   t t  }d|v r|d |S )Nr   )listr<   __dir__remove)r>   
attributesr@   rB   rC   r     s   
zModelMetaclass.__dir__)NTN)rL   r0   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   r   r3   rX   )r   r0   r3   r   )rp   r   rW   r   r3   r   )r   r   r3   rT   )rM   rN   r3   r   )r3   r   )r3   r   )rD   rE   rF   r~   typingTYPE_CHECKINGr   classmethodr   r   staticmethodrx   propertyr   r   r   rH   rB   rB   r@   rC   rK   :   s"     

rK   r>   r-   	__contextr   r3   r4   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.
    __pydantic_private__N)r   r`   r   get_defaultr	   object_setattr)r>   r   pydantic_privater   private_attrdefaultrB   rB   rC   r[     s   	r[   rO   rP   rM   rN   Callable[..., Any] | Nonec                 C  s8   d| v r| d S ddl m} 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.r^   r   r,   N)r   r-   r   r^   )rO   rM   r-   r^   rB   rB   rC   r}     s   

r}   r|   base_class_varsset[str]base_class_fieldsdict[str, ModelPrivateAttr]c              	     s  ddl m}m m} |t  }i }| di }d|v sd| v r#tdt }	t| 	 D ]\}
}|
dkr5q,t
|trJ|j| d krJ|j| d rJq,t
||sU|jjd	kr[|	|
 q,t
| r|
d
rmtd|
dt|
r~tdd|
 d|
d|||
< | |
= q,t
||rt|
s|
dpd}td|d|
d|
d
rq,t|
r|
|vst||
 s||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 ]M\}}t|rH||vrH||	vrHt|sH||vrHt|ddd	krHt|rCt|^}}t fdd|D d}|durC|||< 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____root__zUTo define root models, use `pydantic.RootModel` rather than a field called '__root__'rY   rE   rF   	functools__zXPrivate attributes must not use dunder names; use a single underscore prefix instead of rm   zJPrivate attributes must not use valid field names; use sunder names, e.g. _z instead of 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 re   )r7   )rg   r1   r+   rB   rC   ri     s    z$inspect_namespace.<locals>.<genexpr>)fieldsr*   r+   r   default_ignored_typesr6   r   r   r   r   r7   rX   rE   rF   
startswithrA   add	NameErrorr   lstripr   r$   r   r   r#   typing_extensionsget_argsnext)rO   r|   r   r   r*   r   all_ignored_typesr   raw_annotationsignored_namesvar_namevaluesuggested_nameann_nameann_typer   metadatar   rB   r   rC   r{   &  s   












r{   r   type[BaseModel]c                 C  s@   t |d}t| }|d tjhv st|dd |jkr|| _d S d S )Nrr   __code__)r   make_hash_funcr2   rr   r   r   )r   rM   base_hash_funcnew_hash_funcrB   rB   rC   r     s
   
 
r   c                   s0   | j rtj| j   ndd  d	 fdd}|S )
Nc                 S  s   dS )Nr   rB   )r   rB   rB   rC   <lambda>  s    z make_hash_func.<locals>.<lambda>r>   r   r3   intc                   s6   zt  | jW S  ty   t  t| j Y S w re   )hashr   KeyErrorr'   r   getterrB   rC   	hash_func  s
   z!make_hash_func.<locals>.hash_func)r>   r   r3   r   )r   operator
itemgetterr   )r   r   rB   r   rC   r     s   
r   r   r   rt   c           	      C  sl   t | }t| ||||d\}}|| _| j| |D ]}| j|d}|dur3|jtur3t	| ||j qd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   rM   r   rt   r  r   r   r/   r   rB   rB   rC   r     s   r   )rs   ru   rL   r0   rs   rT   dict[str, Any] | Noneru   rV   c             
   C  s,  t | }t|||}tt|jdd|dd}|jr t| | dS z| | |}	W n! tyI }
 z|r3 t| |d|
j	 d W Y d}
~
dS d}
~
ww |
| }z||	}	W n |jyf   t| | Y dS w |	| _t|	| |pq| j| j|rwdnd||j| _t|	|| _d	| _td
t| 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.
        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)from_dunder_get_core_schemaunpack)ref_moder5   Ncreate_modelr-   T__signature__)initr   r   )r   r   r    r   generate_schemadefer_buildr   __get_pydantic_core_schema__r   r   core_configclean_schemaCollectedInvalidr   r   rE   rF   plugin_settingsr   r
   __pydantic_serializer__r   r&   r!   r   r   r  )r   rL   r   rs   rt   ru   r  
gen_schemahandlerschemaer  rB   rB   rC   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 re   )_wrweakrefref)r>   r   rB   rB   rC   r   <  s   
z_PydanticWeakRef.__init__r3   c                 C  s   | j d u rd S |   S re   )r  r   rB   rB   rC   __call__D  s   
z_PydanticWeakRef.__call__4tuple[Callable, tuple[weakref.ReferenceType | None]]c                 C  s   t |  ffS re   )r  r   rB   rB   rC   
__reduce__J  s   z_PydanticWeakRef.__reduce__N)r   r   )r3   r   )r3   r  )rD   rE   rF   rG   r   r  r  rB   rB   rB   rC   r  +  s
    

r  dc              	   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   )r   resultr/   r1   proxyrB   rB   rC   r   N  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   r7   r  )r   r!  r/   r1   rB   rB   rC   r   b  s   

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#  rB   rB   rC   r   r  s   r   )r>   r-   r   r   r3   r4   )rO   rP   rM   rN   r3   r   )
rO   rP   r|   rN   r   r   r   r   r3   r   )r   r   rM   rN   r3   r4   )r   r   r3   r   )
r   r   rM   rN   r   r   rt   rP   r3   r4   )r   r   rL   r0   r   r   rs   rT   rt   r  ru   rV   r3   rT   )r   r  r3   r  )r3   rN   )XrG   
__future__r   _annotationsr  r   r8   r  abcr   r   r   typesr   r   r   r   r   pydantic_corer	   r
   r   r   errorsr   r   plugin._schema_validatorr   r   r   _configr   _decoratorsr   r   r   _fieldsr   r   r   _generate_schemar   	_genericsr   r   _mock_val_serr   r   _schema_generation_sharedr    
_signaturer!   _typing_extrar"   r#   r$   r%   _utilsr&   r'   _validate_callr(   r   r   r)   PydanticModelFieldr*   r+   r   r-   DeprecationWarningr2   __setattr__r   r   r.   rK   r[   r}   r{   r   r   r   r   r  r   r   r   rB   rB   rB   rC   <module>   sf     
N


u

#U
#
