U
    EZh                  	   @  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 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 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+m,Z, ddl-m.Z.m/Z/m0Z0 ddl1m2Z2 ddl3m4Z4m5Z5 ddl6m7Z7m8Z8 ddl9m:Z: ddl;m<Z< ddl=m>Z> ddl?m@Z@ ddlAmBZBmCZCmDZDmEZEmFZF ddlGmHZHmIZI ejJrd
dlKmLZLmMZMmNZN d
dlKmOZP d
dlKmQZR d
dlSmTZT ne%ZUeV ZPeV ZReVjWZXG dd  d eYZZd!d"d#d$d%d&d'Z[ed(ePeRe[fd)G d*d+ d+eZ\d,d$d-d.d/d0Z]d1d2d3d4d5d6Z^d1d2d7d7d8d9d:d;Z_d<d2d-d=d>d?Z`d<d$d@dAdBZad<d2dCdDd-dEdFdGZbd(dddHd<dIdCdJdDdKdJdLdMdNZcd<d-d@dOdPZdG dQdR dRZeG dSdT dTZfdUdUdVdWdXZgdUdUdVdYdZZhedd[d2d\d]d^ZidS )_z"Private logic for creating models.    )annotationsN)ABCMeta)	lru_cachepartial)FunctionType)AnyCallableGenericLiteralNoReturncast)PydanticUndefinedSchemaSerializer)TypeAliasTypedataclass_transform
deprecatedget_args   )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)PydanticGenericMetadataget_model_typevars_map)import_cached_base_modelimport_cached_field_info)set_model_mocks)
NsResolver)CallbackGetCoreSchemaHandler)generate_pydantic_signature)_make_forward_refeval_type_backportis_annotatedis_classvar_annotationparent_frame_namespace)LazyClassAttributeSafeGetItemProxy)ComputedFieldInfo	FieldInfoModelPrivateAttr)Field)PrivateAttr)	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__)selfr<   r=   existing	__class__ m/home/aprabhat/apps/x.techxrdev.in/venv/lib/python3.8/site-packages/pydantic/_internal/_model_construction.pyrE   =   s    z_ModelNamespaceDict.__setitem__)__name__
__module____qualname____doc__rE   __classcell__rJ   rJ   rH   rK   r8   8   s   r8   FinitzLiteral[False]r   )rR   r>   c                 C  s   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.
    NrJ   rQ   rJ   rJ   rK   NoInitFieldE   s    rS   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ddddd d!Zeddd"d#Zed$dd%d&Zd'd fd(d)Z  ZS )+ModelMetaclassNTr9   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kwargsr>   c                   s  |rB|  |\}}	}
t|||}|j|d< t||j|	|}|sF|
rt||  dk	rxdddd fdd}||d	< nt|d	< |	|d
< |
||d< tdt	 j
| |||f|}t }|j}t|kr|t||k rtjtddd t|jdd |_|j|jkrdnd	|_t||_|r0||_n<t|di ddt|ddpTr^r^tfddD s^ddlm} tfddD }|kr|krd dd |D }|j! d| d|j! d| d }np| }d d!d |D }d"| d#}d$| d%}t|krVd d&d |D |g }|d'|j! d(| d)7 }t"|ddd*|_d|_#|$ D ]\}}|%|| qz|rt&t' |_(t|d+d}t)|t*rt+|}t,|d,}t-|||| |j.rd-|krt/|| t0|||d||d. d/d0 |jj1$ D |_2t3| t	||j4f | |S d1D ]}|5|d qF|d2i 6  t	 j
| |||f|S dS )3a  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_configNr7   r   r;   rF   contextr>   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)rF   re   )original_model_post_initrJ   rK   wrapped_model_post_inity   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_   
parametersrJ   __parameters__c                 3  s   | ]}| kV  qd S NrJ   .0x)ro   rJ   rK   	<genexpr>   s     z)ModelMetaclass.__new__.<locals>.<genexpr>)RootModelRootTypec                 3  s   | ]}| kr|V  qd S rq   rJ   rr   )parent_parametersrJ   rK   ru      s      z, c                 S  s   g | ]
}|j qS rJ   rL   rr   rJ   rJ   rK   
<listcomp>   s     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 rJ   )r9   rr   rJ   rJ   rK   ry      s     ztyping.Generic[]zJAll parameters must be present on typing.Generic; you should inherit from .c                 S  s   g | ]
}|j qS rJ   rx   rr   rJ   rJ   rK   ry      s     z- Note: `typing.Generic` must go last: `class (z): ...`))originargsro   __pydantic_parent_namespace__)parent_namespace__hash__raise_errorsns_resolvercreate_model_modulec                 S  s   i | ]\}}||j qS rJ   )info)rs   r<   r=   rJ   rJ   rK   
<dictcomp>   s     z*ModelMetaclass.__new__.<locals>.<dictcomp>)Z__pydantic_fields_set____pydantic_extra____pydantic_private____annotations__)7_collect_bases_datar   Z	for_modelZconfig_dictinspect_namespaceignored_typesget_model_post_initrf   r   rD   __new__r%   __mro__r	   indexrB   rC   r   getattr__init__Z__pydantic_custom_init__ri   Z__pydantic_post_init__r   buildZ__pydantic_decorators__r_   r@   allZ
root_modelrv   tuplejoinrL   	TypeError__pydantic_complete__items__set_name__build_lenient_weakvaluedictr/   r   rA   dictunpack_lenient_weakvaluedictr(   set_model_fieldsfrozenset_default_hash_funccomplete_model_classZcomputed_fields__pydantic_computed_fields__set_deprecated_descriptorsZ__pydantic_init_subclass__popclear)mcsr\   r]   r^   r_   r`   ra   rb   Zbase_field_names
class_varsZbase_private_attributesconfig_wrapperprivate_attributesrh   clsZ
BaseModel_mrorv   Zmissing_parametersZparameters_strerror_messageZcombined_parametersZgeneric_type_labelZ	bases_strnameobjr   r   Zinstance_slotrH   )rg   ro   rw   rK   r   Q   s    
   


$




zModelMetaclass.__new__)itemr>   c                 C  s,   | j d}|r ||kr || S t|dS )zNThis is necessary to keep attribute access working for class attribute access.rk   N)__dict__r@   AttributeError)rF   r   r   rJ   rJ   rK   __getattr__  s    zModelMetaclass.__getattr__zdict[str, object])r~   rb   r>   c                 O  s   t  S rq   )r8   )r   r~   rb   rJ   rJ   rK   __prepare__
  s    zModelMetaclass.__prepare__)instancer>   c                   s   t |dot |S )zsAvoid calling ABC _abc_subclasscheck unless we're pretty sure.

        See #3829 and python/cpython#92810
        __pydantic_validator__)hasattrrD   __instancecheck__)rF   r   rH   rJ   rK   r     s    z ModelMetaclass.__instancecheck__z6tuple[set[str], set[str], dict[str, ModelPrivateAttr]])r]   r>   c                 C  sj   t  }t }t }i }| D ]D}t||r||k	r|t|di   ||j ||j q|||fS )N__pydantic_fields__)r%   set
issubclassupdater   keysrj   rk   )r]   r7   field_namesr   r   baserJ   rJ   rK   r     s    z"ModelMetaclass._collect_bases_dataEThe `__fields__` attribute is deprecated, use `model_fields` instead.)categoryzdict[str, FieldInfo]r>   c                 C  s   t jdtdd | jS )Nr   r   rm   )rB   rC   r   model_fieldsrF   rJ   rJ   rK   
__fields__$  s    zModelMetaclass.__fields__c                 C  s   t | di S )zGet metadata about the fields defined on the model.

        Returns:
            A mapping of field names to [`FieldInfo`][pydantic.fields.FieldInfo] objects.
        r   r   r   rJ   rJ   rK   r   .  s    zModelMetaclass.model_fieldszdict[str, ComputedFieldInfo]c                 C  s   t | di S )zGet metadata about the computed fields defined on the model.

        Returns:
            A mapping of computed field names to [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] objects.
        r   r   r   rJ   rJ   rK   model_computed_fields7  s    z$ModelMetaclass.model_computed_fieldsz	list[str]c                   s$   t t  }d|kr |d |S )Nr   )listrD   __dir__remove)rF   
attributesrH   rJ   rK   r   @  s    
zModelMetaclass.__dir__)NTN)rL   rM   rN   r   typingTYPE_CHECKINGr   classmethodr   r   staticmethodr   propertyr   r   r   r   r   rP   rJ   rJ   rH   rK   rV   O   s(      " 0
rV   r7   r;   rd   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.
    r   N)r   rk   r   get_defaultr   object_setattr)rF   re   Zpydantic_privater   private_attrdefaultrJ   rJ   rK   rf   G  s    	
rf   rX   rW   zCallable[..., Any] | None)r^   r]   r>   c                 C  s2   d| kr| d S t  }t|d}||jk	r.|S dS )zaGet the `model_post_init` method from the namespace or the class bases, or `None` if not defined.ri   N)r%   r   ri   )r^   r]   r7   ri   rJ   rJ   rK   r   Y  s    

r   zset[str]zdict[str, ModelPrivateAttr])r^   r   base_class_varsbase_class_fieldsr>   c              
     s8  ddl m m} t }|t  }i }| di }d|ks@d| krHtdt }	t| 	 D ]\}
}|
dksZ|
dkrxqZqZt
|tr|j| d krd	| kr|j| d	 rqZqZt
||s|jjd
kr|	|
 qZqZt
| r,|
drtd|
dn$t|
rtdd|
 d|
d|||
< | |
= qZt
||rjt|
sj|
dpPd}td|d|
dqZ|
drzqZqZt|
r|
|kst||
 s0t ||d||
< | |
= qZ|
|krqZqZ|
|krZ|
|krtd|
dddqZt
||rtd|
dddqZtd|
 d|d|
 dddqZ|	 D ]\}}t|r:||kr:||	kr:t|s:||kr:t|ddd
kr:t
|trtd}|dk	rz tt|dd d!|j|jd"}W n ttfk
r   Y nX t |r&t!|^}}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   )r4   r6   r   Z__root__zUTo define root models, use `pydantic.RootModel` rather than a field called '__root__'rc   r   rM   rN   	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_argumentZis_class)globalnslocalnsc                 3  s   | ]}t | r|V  qd S rq   )rA   )rs   r=   r4   rJ   rK   ru     s     
 z$inspect_namespace.<locals>.<genexpr>)#fieldsr4   r6   r&   default_ignored_typesr@   r   r   r   r   rA   r[   rM   rN   
startswithrI   add	NameErrorr    lstripr!   r.   r   r   r   r9   sys	_getframer,   r+   	f_globalsf_localsr-   r   next)r^   r   r   r   r6   r3   Zall_ignored_typesr   Zraw_annotationsignored_namesvar_namevalueZsuggested_nameZann_nameZann_typeframer   metadatar   rJ   r   rK   r   e  s    









 





r   rl   )r   r]   r>   c                 C  s<   t |d}t| }|d tjhks2t|dd |jkr8|| _d S )Nr   __code__)r   make_hash_funcr:   r   r   r   )r   r]   Zbase_hash_funcZnew_hash_funcrJ   rJ   rK   r     s    
 r   )r   r>   c                   s6   | j rtj| j   ndd  ddd fdd}|S )Nc                 S  s   dS )Nr   rJ   )r   rJ   rJ   rK   <lambda>      z make_hash_func.<locals>.<lambda>r   int)rF   r>   c                   s<   zt  | jW S  tk
r6   t  t| j Y S X d S rq   )hashr   KeyErrorr1   r   getterrJ   rK   	hash_func  s    z!make_hash_func.<locals>.hash_func)r   operator
itemgetterr   )r   r   rJ   r   rK   r     s    
r   r   zNsResolver | None)r   r]   r   r   r>   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.__pydantic_fields__` and `cls.__class_vars__`.

    Args:
        cls: BaseModel or dataclass.
        bases: Parents of the class, generally `cls.__bases__`.
        config_wrapper: The config wrapper instance.
        ns_resolver: Namespace resolver to use when getting model annotations.
    )typevars_mapN)
r$   r   r   rj   r   rk   r   r   r   setattr)	r   r]   r   r   r   r   r   r<   r   rJ   rJ   rK   r   
  s    r   r   r9   rY   rZ   )r   r\   r   r   r   r   r>   c             
   C  s<  |j rt| | dS t| }t|||}tt|jdd|dd}z| | |}	W nD tk
r }
 z&|rh t| |d|
j	 d W Y dS d}
~
X Y nX |j
| jd}z||	}	W n" |jk
r   t| | Y dS X |	| _t|	| |p| j| j|rd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.
        cls_name: The model or dataclass name.
        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`.
    F)Zfrom_dunder_get_core_schemaunpack)Zref_moder?   N)titleZcreate_modelr7   T__signature__)rR   r   populate_by_nameextra)Zdefer_buildr'   r$   r"   r)   r   Zgenerate_schemaZ__get_pydantic_core_schema__r   r   core_configrL   Zclean_schemaZCollectedInvalidZ__pydantic_core_schema__r   rM   rN   Zplugin_settingsr   r   Z__pydantic_serializer__r   r0   r*   r   r   r   r  r   )r   r\   r   r   r   r   r   Z
gen_schemahandlerZschemaer  rJ   rJ   rK   r   +  sd    


	
r   c                 C  s   | j  D ]6\}}|j }dk	r
t|}|| | t| || q
| j D ]J\}}|j }dk	rLtt|j	dsLt||j	}|| | t| || qLd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   fieldZ
field_infomsgdescZcomputed_field_inforJ   rJ   rK   r     s    r   c                   @  sf   e Zd ZU dZded< ddddddd	Zd
dddddZdddddddZddd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.
    r9   
field_nameNzproperty | Noner;   )r	  r  r>   c                 C  s   || _ || _d S rq   )r	  r  )rF   r	  r  rJ   rJ   rK   r     s    z#_DeprecatedFieldDescriptor.__init__rl   )r   r   r>   c                 C  s
   || _ d S rq   )r  )rF   r   r   rJ   rJ   rK   r     s    z'_DeprecatedFieldDescriptor.__set_name__zBaseModel | Noneztype[BaseModel] | Noner   )r   obj_typer>   c                 C  sb   |d kr*| j d k	r | j d |S t| jtj| jtjdd | j d k	rV| j ||S |j	| j S )Nr   rm   )
r  __get__r   r  rB   rC   r	  builtinsDeprecationWarningr   )rF   r   r  rJ   rJ   rK   r    s    


z"_DeprecatedFieldDescriptor.__get__r   )r   r   r>   c                 C  s   t | jd S rq   )r   r  )rF   r   r   rJ   rJ   rK   __set__  s    z"_DeprecatedFieldDescriptor.__set__)N)N)	rL   rM   rN   rO   r   r   r   r  r  rJ   rJ   rJ   rK   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 krd | _ nt|| _ d S rq   )_wrweakrefref)rF   r   rJ   rJ   rK   r     s    z_PydanticWeakRef.__init__r   c                 C  s   | j d krd S |   S d S rq   )r  r   rJ   rJ   rK   __call__  s    
z_PydanticWeakRef.__call__z4tuple[Callable, tuple[weakref.ReferenceType | None]]c                 C  s   t |  ffS rq   )r  r   rJ   rJ   rK   
__reduce__  s    z_PydanticWeakRef.__reduce__N)rL   rM   rN   rO   r   r  r  rJ   rJ   rJ   rK   r    s   r  zdict[str, Any] | None)dr>   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  resultr<   r=   proxyrJ   rJ   rK   r     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   rA   r  )r  r  r<   r=   rJ   rJ   rK   r     s    


r   )maxsizer   c                  C  s<   ddl m}  ttttt| tg}tj	dkr4|
tj t|S )Nr   )r2   )      )r   r2   r   r   r   r   r   r   r   version_infoappendr   r   )r2   r   rJ   rJ   rK   r     s    

r   )jrO   
__future__r   Z_annotationsr  r   r   r   rB   r  abcr   r   r   r   typesr   r   r   r	   r
   r   r   Zpydantic_corer   r   typing_extensionsr   r   r   r   errorsr   r   Zplugin._schema_validatorr   r   r   _configr   Z_decoratorsr   r   r   r   _fieldsr   r    r!   Z_generate_schemar"   Z	_genericsr#   r$   Z_import_utilsr%   r&   Z_mock_val_serr'   Z_namespace_utilsr(   Z_schema_generation_sharedr)   
_signaturer*   Z_typing_extrar+   r,   r-   r.   r/   Z_utilsr0   r1   r   r   r2   r3   r4   r5   ZPydanticModelFieldr6   ZPydanticModelPrivateAttrmainr7   r  r:   __setattr__r   r   r8   rS   rV   rf   r   r   r   r   r   r   r   r  r  r   r   r   rJ   rJ   rJ   rK   <module>   sz    
 x 	&]%#