U
    em                  	   @  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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	ZLd#d$d%d&d'd(ZMd)d*d+d,d-d.ZNd)d*d/d/d0d1d2d3ZOd4d*d%d5d6d7ZPd4d$d8d9d:ZQd4d*d;d)d%d<d=d>ZRddd?d4d@d;dAdBdCdAdDdEdFZSG dGdH dHZTdBdBdIdJdKZUdBdBdIdLdMZVd*dNdOdPZWdS )Qz"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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>||k	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__)selfr2   r3   existing	__class__ J/tmp/pip-unpacked-wheel-6q_yhcy8/pydantic/_internal/_model_construction.pyr;   2   s    z_ModelNamespaceDict.__setitem__)__name__
__module____qualname____doc__r;   __classcell__r@   r@   r>   rA   r.   -   s   r.   T)Zkw_only_defaultZ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ddddd d!Zd"d fd#d$Z  ZS )&ModelMetaclassNTr/   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kwargsr4   c                   s  |r|  |\}}	}
t|||}|j|d< t||j|	|}|r|t||  dk	rtdddd fdd}||d	< nt|d	< |	|d
< |
||d< t j	| |||f|}ddl
m} |j}t|kr|t||k rtjtddd t|jdd |_|j|jkr
dnd	|_t||_|r*||_nt|di ddt|ddpNrrtfddD stfddD  }ddd |D }d| d}d| d}t|krdd d |D |g }|d!|j d"| d#7 }t |ddd$|_d|_!|" D ]\}}|#|| q|rDt$t% |_&t|d%d}t'|t(rdt)|}t*||}t+|||| |j,rd&|krt-|| t.|||d||d' d(d) |jj/" D |_0t||j1f | |S t j	| |||f|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   r1   )r<   _ModelMetaclass__contextr4   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<   rU   )original_model_post_initr@   rA   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__FrP   
parametersr@   __parameters__c                 3  s   | ]}| kV  qd S Nr@   .0x)r]   r@   rA   	<genexpr>   s     z)ModelMetaclass.__new__.<locals>.<genexpr>c                 3  s   | ]}| kr|V  qd S r_   r@   r`   )parent_parametersr@   rA   rc      s      z, c                 S  s   g | ]}t |qS r@   )r/   r`   r@   r@   rA   
<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 r@   )rB   r`   r@   r@   rA   re      s     z- Note: `typing.Generic` must go last: `class (z): ...`))originargsr]   __pydantic_parent_namespace____hash__)raise_errorstypes_namespacecreate_model_modulec                 S  s   i | ]\}}||j qS r@   )info)ra   r2   r3   r@   r@   rA   
<dictcomp>   s      z*ModelMetaclass.__new__.<locals>.<dictcomp>)2_collect_bases_datar   Z	for_modelZconfig_dictinspect_namespaceignored_typesget_model_post_initrV   r:   __new__mainr-   __mro__r   indexr8   r9   r   getattr__init__Z__pydantic_custom_init__rY   Z__pydantic_post_init__r   buildZ__pydantic_decorators__rP   r6   alltuplejoinrB   	TypeError__pydantic_complete__items__set_name__build_lenient_weakvaluedictr%   rk   r7   dictunpack_lenient_weakvaluedictr"   set_model_fieldsfrozenset_default_hash_funccomplete_model_classZcomputed_fieldsZmodel_computed_fieldsZ__pydantic_init_subclass__)ZmcsrM   rN   rO   rP   rQ   rR   rS   Zbase_field_names
class_varsZbase_private_attributesconfig_wrapperprivate_attributesrX   clsr-   mroZcombined_parametersZparameters_strZgeneric_type_labelerror_messageZ	bases_strnameobjZparent_namespacern   r>   )rW   r]   rd   rA   rv   <   s    
   

$



zModelMetaclass.__new__)itemr4   c                 C  sd   | j d}|r ||kr || S |dkrXt| dd}t|trX| }|dk	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__r6   rz   r7   r   ZrebuildAttributeError)r<   r   r   Zmaybe_mock_validatorZrebuilt_validatorr@   r@   rA   __getattr__   s    

zModelMetaclass.__getattr__zdict[str, object])rj   rS   r4   c                 O  s   t  S r_   )r.   )r   rj   rS   r@   r@   rA   __prepare__   s    zModelMetaclass.__prepare__)instancer4   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>   r@   rA   r      s    z ModelMetaclass.__instancecheck__z6tuple[set[str], set[str], dict[str, ModelPrivateAttr]])rN   r4   c                 C  sp   ddl m} t }t }i }| D ]D}t||r ||k	r |t|di   ||j ||j q |||fS )Nr   r,   model_fields)	rw   r-   set
issubclassupdaterz   keysrZ   r[   )rN   r-   field_namesr   r   baser@   r@   rA   rr      s    z"ModelMetaclass._collect_bases_dataEThe `__fields__` attribute is deprecated, use `model_fields` instead.)categoryzdict[str, FieldInfo]r4   c                 C  s   t dt | jS )Nr   )r8   r9   r   r   r<   r@   r@   rA   
__fields__   s
     zModelMetaclass.__fields__z	list[str]c                   s$   t t  }d|kr |d |S )Nr   )listr:   __dir__remove)r<   
attributesr>   r@   rA   r     s    
zModelMetaclass.__dir__)NTN)rB   rC   rD   rv   typingTYPE_CHECKINGr   classmethodr   r   staticmethodrr   propertyr   r   r   rF   r@   r@   r>   rA   rG   :   s       " 
rG   r-   r   r1   )r<   	__contextr4   c                 C  sP   t | dddkrLi }| j D ] \}}| }|tk	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)rz   r[   r   get_defaultr	   object_setattr)r<   r   Zpydantic_privater   private_attrdefaultr@   r@   rA   rV     s    	
rV   rI   rH   zCallable[..., Any] | None)rO   rN   r4   c                 C  s8   d| kr| d S ddl m} t|d}||jk	r4|S dS )zaGet the `model_post_init` method from the namespace or the class bases, or `None` if not defined.rY   r   r,   N)rw   r-   r   rY   )rO   rN   r-   rY   r@   r@   rA   ru     s    

ru   zset[str]zdict[str, ModelPrivateAttr])rO   rt   base_class_varsbase_class_fieldsr4   c              	     s  ddl m}m m} |t  }i }| di }d|ks>d| k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|
|kst||
 s||d||
< | |
= qX|
|krqXqX|
|krX|
|krtd|
dddqXt
||rtd|
dddqXtd|
 d|d|
 dddqX|	 D ]\}}t|r"||kr"||	kr"t|s"||kr"t|ddd	kr"t|rt|^}}t fdd|D d}|dk	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__'rT   rC   rD   	functools__zXPrivate attributes must not use dunder names; use a single underscore prefix instead of rg   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 r_   )r7   )ra   r3   r+   r@   rA   rc     s     
 z$inspect_namespace.<locals>.<genexpr>)fieldsr*   r+   r   default_ignored_typesr6   r   r   r   r   r7   rL   rC   rD   
startswithr?   add	NameErrorr   lstripr   r$   r   rz   r#   typing_extensionsget_argsnext)rO   rt   r   r   r*   r   Zall_ignored_typesr   Zraw_annotationsignored_namesvar_namevalueZsuggested_nameZann_nameZann_typer   metadatar   r@   r   rA   rs   &  s    









 

rs   ztype[BaseModel])r   rN   r4   c                 C  s<   t |d}t| }|d tjhks2t|dd |jkr8|| _d S )Nrl   __code__)r   make_hash_funcr0   rl   rz   r   )r   rN   Zbase_hash_funcZnew_hash_funcr@   r@   rA   r     s    
 r   )r   r4   c                   s6   | j rtj| j   ndd  ddd fdd}|S )Nc                 S  s   dS )Nr   r@   )r   r@   r@   rA   <lambda>      z make_hash_func.<locals>.<lambda>r   int)r<   r4   c                   s<   zt  | jW S  tk
r6   t  t| j Y S X d S r_   )hashr   KeyErrorr'   r   getterr@   rA   	hash_func  s    z!make_hash_func.<locals>.hash_func)r   operator
itemgetterr   )r   r   r@   r   rA   r     s    
r   r   )r   rN   r   rn   r4   c           	      C  sl   t | }t| ||||d\}}|| _| j| |D ]2}| j|d}|dk	r4|jtk	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   rZ   r   r[   popr   r	   setattr)	r   rN   r   rn   r   r   r   r2   r   r@   r@   rA   r     s    r   )rm   ro   r/   rJ   zdict[str, Any] | NonerK   )r   rM   r   rm   rn   ro   r4   c             
   C  s0  t | }t|||}tt|jdd|dd}|jr@t| | dS z| | |}	W nD tk
r }
 z&|rh t| |d|
j	 d W Y dS d}
~
X Y nX |
| }z||	}	W n" |jk
r   t| | Y dS X |	| _t|	| |p| j| j|rd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)Zfrom_dunder_get_core_schemaunpack)Zref_moder5   NZcreate_modelr-   T__signature__)initr   r   )r   r   r    r   Zgenerate_schemaZdefer_buildr   Z__get_pydantic_core_schema__r   r   core_configZclean_schemaZCollectedInvalidr   r   rC   rD   Zplugin_settingsr   r
   Z__pydantic_serializer__r   r&   r!   r{   r   r   )r   rM   r   rm   rn   ro   r   Z
gen_schemahandlerZschemaer   r@   r@   rA   r     sX    



	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 krd | _ nt|| _ d S r_   )_wrweakrefref)r<   r   r@   r@   rA   r{   <  s    z_PydanticWeakRef.__init__r   c                 C  s   | j d krd S |   S d S r_   )r   r   r@   r@   rA   __call__D  s    
z_PydanticWeakRef.__call__z4tuple[Callable, tuple[weakref.ReferenceType | None]]c                 C  s   t |  ffS r_   )r   r   r@   r@   rA   
__reduce__J  s    z_PydanticWeakRef.__reduce__N)rB   rC   rD   rE   r{   r   r   r@   r@   r@   rA   r   +  s   r   )dr4   c              	   C  sT   | dkrdS i }|   D ]6\}}zt|}W n tk
rD   |}Y nX |||< 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   resultr2   r3   proxyr@   r@   rA   r   N  s    

r   c                 C  sP   | dkrdS i }|   D ]2\}}t|trB| }|dk	rJ|||< q|||< q|S )zAInverts the transform performed by `build_lenient_weakvaluedict`.N)r   r7   r   )r   r   r2   r3   r@   r@   rA   r   b  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   r@   r@   rA   r   r  s    r   )XrE   
__future__r   Z_annotationsr   r   r8   r   abcr   r   r   typesr   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   Z	_genericsr   r   Z_mock_val_serr   r   Z_schema_generation_sharedr    
_signaturer!   Z_typing_extrar"   r#   r$   r%   _utilsr&   r'   Z_validate_callr(   r   r   r)   ZPydanticModelFieldr*   r+   rw   r-   DeprecationWarningr0   __setattr__r   r   r.   rG   rV   ru   rs   r   r   r   r   r   r   r   r   r@   r@   r@   rA   <module>   sd    Nu#U#