U
    nËjá4  ã                   @  s�  U 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	m
Z
mZ ddlm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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#m$Z$ ddl%m&Z& ej'�rdZ(de)d< dZ*de)d< ddl+m,Z, e-e.e/e0e1e2e3e$j4eeeej5eee6j7e8j7hZ9de)d< e:e;e<e=e>e	e
ehZ?de)d< dddœdd„Z@dddœd d!„ZAdd"dd#œd$d%„ZBdddd&œd'd(„ZCdd)d*œd+d,„ZDd-dd.œd/d0„ZEed1ƒZFd2d2d2d3œd4d5„ZGd6dd7d8œd9d:„ZHed;ƒZIe0d<œd=d>d?d@œdAdB„ZJG dCdD„ dDe#jKƒZLej'�r4d-dEd;dFœdGdH„ZMnG dIdH„ dHƒZMedJƒZNdJdJdKœdLdM„ZOePƒ ZQdNdNddOœdPdQ„ZRejSdRdS�G dTdU„ dUƒƒZTdS )Vz�Bucket of reusable internal utilities.

This should be reduced as much as possible with functions only used in one place, moved to that place.
é    )ÚannotationsN)ÚOrderedDictÚdefaultdictÚdeque)Údeepcopy)Úcached_property)Ú	Parameter)Úzip_longest)ÚBuiltinFunctionTypeÚCodeTypeÚFunctionTypeÚGeneratorTypeÚ
LambdaTypeÚ
ModuleType)ÚAnyÚCallableÚMappingÚTypeVar)Ú	TypeAliasÚ	TypeGuardé   )Ú_reprÚ_typing_extra)Úimport_cached_base_modelz3typing.Mapping[int, Any] | typing.Mapping[str, Any]r   ÚMappingIntStrAnyz1typing.AbstractSet[int] | typing.AbstractSet[str]ÚAbstractSetIntStré   )Ú	BaseModelzset[type[Any]]ÚIMMUTABLE_NON_COLLECTIONS_TYPESÚBUILTIN_COLLECTIONSr   Úbool)ÚparamÚreturnc                 C  s   | j tjtjfkS )aZ  Return whether the parameter accepts a positional argument.

    ```python {test="skip" lint="skip"}
    def func(a, /, b, *, c):
        pass

    params = inspect.signature(func).parameters
    can_be_positional(params['a'])
    #> True
    can_be_positional(params['b'])
    #> True
    can_be_positional(params['c'])
    #> False
    ```
    )Úkindr   ÚPOSITIONAL_ONLYÚPOSITIONAL_OR_KEYWORD)r!   © r&   ú=/tmp/pip-unpacked-wheel-zvl9l234/pydantic/_internal/_utils.pyÚcan_be_positionalC   s    r(   r   ©Úvr"   c                 C  s   t | ttttttfƒS ©N)Ú
isinstanceÚlistÚtupleÚsetÚ	frozensetr   r   ©r*   r&   r&   r'   Úsequence_likeV   s    r2   z(type[Any] | tuple[type[Any], ...] | None)ÚoÚclass_or_tupler"   c                 C  s(   zt | |ƒW S  tk
r"   Y dS X d S ©NF)r,   Ú	TypeError)r3   r4   r&   r&   r'   Úlenient_isinstanceZ   s    r7   )Úclsr4   r"   c                 C  sD   zt | tƒot| |ƒW S  tk
r>   t | tjƒr8Y dS ‚ Y nX d S r5   )r,   ÚtypeÚ
issubclassr6   r   ZWithArgsTypes)r8   r4   r&   r&   r'   Úlenient_issubclassa   s    r;   zTypeGuard[type[BaseModel]])r8   r"   c                 C  s   t ƒ }t| |ƒo| |k	S )zŒReturns true if cls is a _proper_ subclass of BaseModel, and provides proper type-checking,
    unlike raw calls to lenient_issubclass.
    )r   r;   )r8   r   r&   r&   r'   Úis_model_classj   s    r<   Ústr)Ú
identifierr"   c                 C  s   |   ¡ ot | ¡ S )z¦Checks that a string is a valid identifier and not a Python keyword.
    :param identifier: The identifier to test.
    :return: True if the identifier is valid.
    )ÚisidentifierÚkeywordÚ	iskeyword)r>   r&   r&   r'   Úis_valid_identifiers   s    rB   ÚKeyTypezdict[KeyType, Any])ÚmappingÚupdating_mappingsr"   c                 G  sd   |   ¡ }|D ]R}| ¡ D ]D\}}||krTt|| tƒrTt|tƒrTt|| |ƒ||< q|||< qq|S r+   )ÚcopyÚitemsr,   ÚdictÚdeep_update)rD   rE   Zupdated_mappingZupdating_mappingÚkr*   r&   r&   r'   rI   ~   s     rI   zdict[Any, Any]ÚNone)rD   Úupdater"   c                 K  s   |   dd„ | ¡ D ƒ¡ d S )Nc                 S  s   i | ]\}}|d k	r||“qS r+   r&   )Ú.0rJ   r*   r&   r&   r'   Ú
<dictcomp>Š   s       z#update_not_none.<locals>.<dictcomp>)rL   rG   )rD   rL   r&   r&   r'   Úupdate_not_none‰   s    rO   ÚT)Úname_factoryzlist[T] | tuple[T, ...]ztyping.Callable[[T], str]zlist[T])Ú
input_listrQ   r"   c                C  sJ   g }g }| D ]8}||ƒ}||kr6|  |¡ |  |¡ q||| |¡< q|S )z£Make a list unique while maintaining order.
    We update the list if another one with the same name is set
    (e.g. model validator overridden in subclass).
    )ÚappendÚindex)rR   rQ   ÚresultZresult_namesr*   Zv_namer&   r&   r'   Úunique_list�   s    	
rV   c                   @  sÌ   e Zd ZdZdZddddœdd„Zdd	d
œdd„Zdd	d
œdd„Zdddœdd„Zddddœdd„Z	e
d,ddd	ddœdd„ƒZedddœdd „ƒZe
ddd!œd"d#„ƒZedd	d$œd%d&„ƒZd'd(œd)d*„Zd+S )-Ú
ValueItemszOClass for more convenient calculation of excluded or included fields on values.)Ú_itemsÚ_typer   z$AbstractSetIntStr | MappingIntStrAnyrK   )ÚvaluerG   r"   c                 C  s2   |   |¡}t|ttfƒr(|  |t|ƒ¡}|| _d S r+   )Ú_coerce_itemsr,   r-   r.   Ú_normalize_indexesÚlenrX   )ÚselfrZ   rG   r&   r&   r'   Ú__init__«   s    
zValueItems.__init__r    )Úitemr"   c                 C  s   |   | j |¡¡S )zWCheck if item is fully excluded.

        :param item: key or index of a value
        )Úis_truerX   Úget©r^   r`   r&   r&   r'   Úis_excluded³   s    zValueItems.is_excludedc                 C  s
   || j kS )z`Check if value is contained in self._items.

        :param item: key or index of value
        ©rX   rc   r&   r&   r'   Úis_includedº   s    zValueItems.is_includedz	int | strz+AbstractSetIntStr | MappingIntStrAny | None)Úer"   c                 C  s   | j  |¡}|  |¡s|S dS )z�:param e: key or index of element on value
        :return: raw values for element if self._items is dict and contain needed element
        N)rX   rb   ra   )r^   rg   r`   r&   r&   r'   Úfor_elementÁ   s    zValueItems.for_elementr   Úintzdict[int | str, Any])rG   Úv_lengthr"   c           	      C  s
  i }d}|  ¡ D ]�\}}t|tjƒsPt|tjƒsP|  |¡sPtd|› d|j› �ƒ‚|dkrd|  |¡}qt|t	ƒsvtdƒ‚|dk r†|| n|}|  
|| |¡¡||< q|sª|S |  |¡rÒt|ƒD ]}| |d¡ q¼|S t|ƒD ]*}| |i ¡}|  |¡sÚ|  
||¡||< qÚ|S )a]  :param items: dict or set of indexes which will be normalized
        :param v_length: length of sequence indexes of which will be

        >>> self._normalize_indexes({0: True, -2: True, -1: True}, 4)
        {0: True, 2: True, 3: True}
        >>> self._normalize_indexes({'__all__': True}, 4)
        {0: True, 1: True, 2: True, 3: True}
        Nz,Unexpected type of exclude value for index "z" Ú__all__z€Excluding fields from a sequence of sub-models or dicts must be performed index-wise: expected integer keys or keyword "__all__"r   .)rG   r,   Útypingr   ÚAbstractSetra   r6   Ú	__class__Ú_coerce_valueri   Úmergerb   ÚrangeÚ
setdefault)	r^   rG   rj   Znormalized_itemsZ	all_itemsÚir*   Znormalized_iÚnormalized_itemr&   r&   r'   r\   È   s2    	"

ÿ

zValueItems._normalize_indexesF)ÚbaseÚoverrideÚ	intersectr"   c                   sÎ   |   ˆ¡‰|   ˆ ¡‰ ˆdkr ˆ S |  ˆ ¡s2ˆ dkr6ˆS |  ˆ¡rL|rHˆ S ˆS |rv‡fdd„ˆ D ƒ‡ fdd„ˆD ƒ }ntˆ ƒ‡ fdd„ˆD ƒ }i }|D ]0}| jˆ  |¡ˆ |¡|d�}|dk	r˜|||< q˜|S )aH  Merge a `base` item with an `override` item.

        Both `base` and `override` are converted to dictionaries if possible.
        Sets are converted to dictionaries with the sets entries as keys and
        Ellipsis as values.

        Each key-value pair existing in `base` is merged with `override`,
        while the rest of the key-value pairs are updated recursively with this function.

        Merging takes place based on the "union" of keys if `intersect` is
        set to `False` (default) and on the intersection of keys if
        `intersect` is set to `True`.
        Nc                   s   g | ]}|ˆ kr|‘qS r&   r&   ©rM   rJ   )rv   r&   r'   Ú
<listcomp>  s      z$ValueItems.merge.<locals>.<listcomp>c                   s   g | ]}|ˆ kr|‘qS r&   r&   rx   ©ru   r&   r'   ry     s      c                   s   g | ]}|ˆ kr|‘qS r&   r&   rx   rz   r&   r'   ry   	  s      )rw   )ro   ra   r-   rp   rb   )r8   ru   rv   rw   Z
merge_keysÚmergedrJ   Zmerged_itemr&   )ru   rv   r'   rp   í   s"    


&
zValueItems.merge)rG   r"   c                 C  sF   t | tjƒrn4t | tjƒr(t | d¡} nt| ddƒ}td|› �ƒ‚| S )N.rn   z???z!Unexpected type of exclude value )r,   rl   r   rm   rH   ÚfromkeysÚgetattrr6   )rG   Ú
class_namer&   r&   r'   r[     s    zValueItems._coerce_items)rZ   r"   c                 C  s    |d ks|   |¡r|S |  |¡S r+   )ra   r[   )r8   rZ   r&   r&   r'   ro     s    zValueItems._coerce_valuer)   c                 C  s   | dkp| dkS )NT.r&   r1   r&   r&   r'   ra   $  s    zValueItems.is_truez_repr.ReprArgs©r"   c                 C  s   d | j fgS r+   re   ©r^   r&   r&   r'   Ú__repr_args__(  s    zValueItems.__repr_args__N)F)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú	__slots__r_   rd   rf   rh   r\   Úclassmethodrp   Ústaticmethodr[   ro   ra   r�   r&   r&   r&   r'   rW   ¦   s    %%
rW   zCallable[[], T]©ÚnameÚ	get_valuer"   c                 C  s   d S r+   r&   ©rŠ   r‹   r&   r&   r'   ÚLazyClassAttribute.  ó    r�   c                   @  sF   e Zd ZdZddddœdd„Zedd	œd
d„ƒZddddœdd„ZdS )r�   z­A descriptor exposing an attribute only accessible on a class (hidden from instances).

        The attribute is lazily computed and cached during the first access.
        r=   zCallable[[], Any]rK   r‰   c                 C  s   || _ || _d S r+   rŒ   )r^   rŠ   r‹   r&   r&   r'   r_   8  s    zLazyClassAttribute.__init__r   r   c                 C  s   |   ¡ S r+   )r‹   r€   r&   r&   r'   rZ   <  s    zLazyClassAttribute.valuez	type[Any])ÚinstanceÚownerr"   c                 C  s*   |d kr| j S t| j›d|j›d�ƒ‚d S )Nz attribute of z is class-only)rZ   ÚAttributeErrorrŠ   r‚   )r^   r�   r�   r&   r&   r'   Ú__get__@  s    zLazyClassAttribute.__get__N)r‚   rƒ   r„   r…   r_   r   rZ   r’   r&   r&   r&   r'   r�   2  s
   ÚObj)Úobjr"   c              
   C  s\   | j }|tkr| S z&| s6|tkr6|tkr,| n|  ¡ W S W n tttfk
rR   Y nX t| ƒS )z¬Return type as is for immutable built-in types
    Use obj.copy() for built-in empty collections
    Use copy.deepcopy() for non-empty collections and unknown objects.
    )	rn   r   r   r.   rF   r6   Ú
ValueErrorÚRuntimeErrorr   )r”   Zobj_typer&   r&   r'   Úsmart_deepcopyI  s    r—   ztyping.Iterable[Any])ÚleftÚrightr"   c                 C  s*   t | |td�D ]\}}||k	r dS qdS )a  Check that the items of `left` are the same objects as those in `right`.

    >>> a, b = object(), object()
    >>> all_identical([a, b, a], [a, b, a])
    True
    >>> all_identical([a, b, [a]], [a, b, [a]])  # new list object, while "equal" is not "identical"
    False
    )Ú	fillvalueFT)r	   Ú	_SENTINEL)r˜   r™   Z	left_itemZ
right_itemr&   r&   r'   Úall_identical_  s    	rœ   T)Úfrozenc                   @  sD   e Zd ZU dZdZded< dddœdd	„Zejr@dd
dœdd„Z	dS )ÚSafeGetItemProxyz¦Wrapper redirecting `__getitem__` to `get` with a sentinel value as default

    This makes is safe to use in `operator.itemgetter` when some keys may be missing
    )ÚwrappedzMapping[str, Any]rŸ   r=   r   )Úkeyr"   c                C  s   | j  |t¡S r+   )rŸ   rb   r›   ©r^   r    r&   r&   r'   Ú__getitem__{  s    zSafeGetItemProxy.__getitem__r    c                C  s   | j  |¡S r+   )rŸ   Ú__contains__r¡   r&   r&   r'   r£   „  s    zSafeGetItemProxy.__contains__N)
r‚   rƒ   r„   r…   r†   Ú__annotations__r¢   rl   ÚTYPE_CHECKINGr£   r&   r&   r&   r'   rž   n  s   
rž   )Ur…   Ú
__future__r   Z_annotationsZdataclassesr@   rl   ÚweakrefÚcollectionsr   r   r   rF   r   Ú	functoolsr   Úinspectr   Ú	itertoolsr	   Útypesr
   r   r   r   r   r   r   r   r   r   Ztyping_extensionsr   r   Ú r   r   Z_import_utilsr   r¥   r   r¤   r   Úmainr   ri   ÚfloatÚcomplexr=   r    Úbytesr9   ZNoneTypeÚrefÚNotImplementedrn   ÚEllipsisr   r-   r/   r.   r0   rH   r   r(   r2   r7   r;   r<   rB   rC   rI   rO   rP   rV   ZRepresentationrW   r�   r“   r—   Úobjectr›   rœ   Z	dataclassrž   r&   r&   r&   r'   Ú<module>   sˆ    íø		ý 
