
    hs                       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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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 ej<                  dk  r ed      Z  ee!      Z"nddlm"Z" ddlm Z  ej<                  dk\  rddl#Z#erddl$m%Z% ejL                  Z'ejL                  Z(d:dZ)d;dZ*d;dZ+d:dZ,d:dZ- ej\                  d      Z/d:dZ0ejb                  Z2ejb                  Z3d:dZ4de ejj                  d   ejj                  d   fZ6de7d<   d:dZ8d:dZ9eZ:d:dZ;ej<                  dk  rejx                  ejz                  fZ>de7d<   n(ejx                  ejz                  ej~                  fZ>de7d<   ej                  ZAde7d <   d!d"d#d<d$ZBd=d%ZCd>d&ZDdd'	 	 	 	 	 d?d(ZEdd'	 	 	 	 	 d@d)ZF	 	 dA	 	 	 	 	 	 	 dBd*ZG	 	 dA	 	 	 	 	 	 	 dCd+ZH ed,d-      	 	 dA	 	 	 	 	 	 	 dCd.       ZI	 	 	 dD	 	 	 	 	 	 	 	 	 dEd/ZJ	 	 	 dD	 	 	 	 	 	 	 	 	 dEd0ZK	 	 	 dD	 	 	 	 	 	 	 	 	 dEd1ZLdFd2ZMdddd3	 	 	 	 	 	 	 	 	 dGd4ZNej<                  d5k  sdej<                  cxk  rd6k  rn n	 dHd"d7	 	 	 	 	 	 	 dId8ZOnej                  ZOej<                  dk\  rej                  ZQy	 ej                  	 	 	 dJ	 	 	 	 	 	 	 	 	 dKd9       ZQy)LzoLogic for interacting with type annotations, mostly extensions, shims and hacks to wrap Python's typing module.    )annotationsN)partial)TYPE_CHECKINGAnyCallablecast)
deprecatedget_args
get_origin)typing_objects)is_union_origin)version_short   )GlobalsNamespaceMappingNamespace
NsResolverget_module_ns_of   
   )EllipsisType)NoneTyper      )	BaseModelr   c               <    t        |       }|t        u xs |t        u S )zReturn whether the provided argument is a `Annotated` special form.

    ```python {test="skip" lint="skip"}
    is_annotated(Annotated[int, ...])
    #> True
    ```
    )r   _t_annotated_te_annotatedtporigins     ED:\jyotish\venv\Lib\site-packages\pydantic/_internal/_typing_extra.pyis_annotatedr#   -   s"     ^F\!<V}%<<    c               Z    t        j                  t        |             r| j                  S dS )z;Return the type of the `Annotated` special form, or `None`.N)r   r#   r   
__origin__r    s    r"   annotated_typer(   9   s"    *77
2G2==QTQr$   c               ^    t        j                  t        |             rt        |       d   S dS )z@Return the type wrapped by the `Unpack` special form, or `None`.r   N)r   	is_unpackr   r
   r'   s    r"   unpack_typer+   >   s&    ,66z"~F8B<?PDPr$   c                   | t         j                  j                  u xs% t        |       t         j                  j                  u S )zReturn whether the provided argument is the `Hashable` class.

    ```python {test="skip" lint="skip"}
    is_hashable(Hashable)
    #> True
    ```
    )collectionsabcHashabler   r'   s    r"   is_hashabler0   C   s1     )))WZ^{?W?W-WWr$   c                   | t         j                  j                  u xs% t        |       t         j                  j                  u S )a  Return whether the provided argument is a `Callable`, parametrized or not.

    ```python {test="skip" lint="skip"}
    is_callable(Callable[[int], str])
    #> True
    is_callable(typing.Callable)
    #> True
    is_callable(collections.abc.Callable)
    #> True
    ```
    )r-   r.   r   r   r'   s    r"   is_callabler2   P   s1     )))WZ^{?W?W-WWr$   z(((\w+\.)?Annotated\[)?(\w+\.)?ClassVar\[c                  t        j                  |       ryt        |       }t        j                  |      ryt        j                  |      r@| j                  }t        j                  |      st        j                  t        |            ryd}t        | t        j                        r| j                  }t        | t              r| }|t        j                  |      ryy)a?  Return whether the provided argument represents a class variable annotation.

    Although not explicitly stated by the typing specification, `ClassVar` can be used
    inside `Annotated` and as such, this function checks for this specific scenario.

    Because this function is used to detect class variables before evaluating forward references
    (or because evaluation failed), we also implement a naive regex match implementation. This is
    required because class variables are inspected before fields are collected, so we try to be
    as accurate as possible.
    TNF)r   is_classvarr   r#   r&   
isinstancetyping
ForwardRef__forward_arg__str_classvar_rematch)r    r!   r(   str_anns       r"   is_classvar_annotationr=   d   s     !!"%^F!!&)""6*%%n59S9ST^_mTn9oG"f''($$"c|11': r$   c               ^    | t         u s| t        u ryt        |       }|t         u xs |t        u S )zReturn whether the provided argument is a `Final` special form, parametrized or not.

    ```python {test="skip" lint="skip"}
    is_finalvar(Final[int])
    #> True
    is_finalvar(Final)
    #> True
    T)_t_final	_te_finalr   r   s     r"   is_finalvarrA      s2     
X~y^FX49!44r$   ztuple[Any, ...]_NONE_TYPESc                   | t         v S )a  Return whether the argument represents the `None` type as part of an annotation.

    ```python {test="skip" lint="skip"}
    is_none_type(None)
    #> True
    is_none_type(NoneType)
    #> True
    is_none_type(Literal[None])
    #> True
    is_none_type(type[None])
    #> False
    )rB   r'   s    r"   is_none_typerD      s     r$   c               D    ddl m}  || t              xr t        | d      S )zReturn whether the provided argument is a named tuple class.

    The class can be created using `typing.NamedTuple` or `collections.namedtuple`.
    Parametrized generic classes are *not* assumed to be named tuples.
    r   )lenient_issubclass_fields)_utilsrF   tuplehasattr)r    rF   s     r"   is_namedtuplerK      s      +b%(CWR-CCr$   c               V    t        | t        j                  t        j                  f      S N)r5   typesGenericAliasr6   _GenericAliasr'   s    r"   is_generic_aliasrQ      s     b5--v/C/CDEEr$   WithArgsTypestyping_base   F)parent_depthforcec                >   t        j                  |       }|j                  j                  j	                  d      r$t        t        j                  |j                        }|r|j                  S |j                  |j                  j                  dk(  ry|j                  S )a  Fetch the local namespace of the parent frame where this function is called.

    Using this function is mostly useful to resolve forward annotations pointing to members defined in a local namespace,
    such as assignments inside a function. Using the standard library tools, it is currently not possible to resolve
    such annotations:

    ```python {lint="skip" test="skip"}
    from typing import get_type_hints

    def func() -> None:
        Alias = int

        class C:
            a: 'Alias'

        # Raises a `NameError: 'Alias' is not defined`
        get_type_hints(C)
    ```

    Pydantic uses this function when a Pydantic model is being defined to fetch the parent frame locals. However,
    this only allows us to fetch the parent frame namespace and not other parents (e.g. a model defined in a function,
    itself defined in another function). Inspecting the next outer frames (using `f_back`) is not reliable enough
    (see https://discuss.python.org/t/20659).

    Because this function is mostly used to better resolve forward annotations, nothing is returned if the parent frame's
    code object is defined at the module level. In this case, the locals of the frame will be the same as the module
    globals where the class is defined (see `_namespace_utils.get_module_ns_of`). However, if you still want to fetch
    the module globals (e.g. when rebuilding a model, where the frame where the rebuild call is performed might contain
    members that you want to use for forward annotations evaluation), you can use the `force` parameter.

    Args:
        parent_depth: The depth at which to get the frame. Defaults to 2, meaning the parent frame where this function
            is called will be used.
        force: Whether to always return the frame locals, even if the frame's code object is defined at the module level.

    Returns:
        The locals of the namespace, or `None` if it was skipped as per the described logic.
    z<generic parameters ofNz<module>)
sys	_getframef_codeco_name
startswithr   rN   	FrameTypef_backf_locals)rU   rV   frames      r"   parent_frame_namespacera      s{    N MM,'E||&&'?@ U__ell3 ~~
 ||u||33zA>>r$   c                R    | t         S t        | t              rt        | dd      S | S )a  Convert `None` to `NoneType` and strings to `ForwardRef` instances.

    This is a backport of the private `typing._type_convert` function. When
    evaluating a type, `ForwardRef._evaluate` ends up being called, and is
    responsible for making this conversion. However, we still have to apply
    it for the first argument passed to our type evaluation functions, similarly
    to the `typing.get_type_hints` function.
    FTis_argumentis_class)r   r5   r9   _make_forward_ref)args    r"   _type_convertrh     s.     {#s !%$GGJr$   c                    t         j                  dk\  r/t        j                  | t        j                  j
                        S | j                  j                  di       S )a@  Get the annotations for the provided class, accounting for potential deferred forward references.

    Starting with Python 3.14, accessing the `__annotations__` attribute might raise a `NameError` if
    a referenced symbol isn't defined yet. In this case, we return the annotation in the *forward ref*
    format.
    r   )format__annotations__)rX   version_infoannotationlibget_annotationsFormat
FORWARDREF__dict__get)clss    r"   safe_get_annotationsrt   '  sI     7",,S9M9M9X9XYY|| 1266r$   )ns_resolverc                  i }|xs
 t               }t        | j                        D ]  }t        |      }|s|j	                  |      5  |j
                  \  }}|j                         D ]8  \  }}|j                  d      r	 t        |||      ||<   )t        |||      ||<   : 	 ddd        |S # t        $ r
 |df||<   Y Zw xY w# 1 sw Y   xY w)a  Collect annotations from a Pydantic model class, including those from parent classes.

    Args:
        obj: The Pydantic model to inspect.
        ns_resolver: A namespace resolver instance to use. Defaults to an empty instance.

    Returns:
        A dictionary mapping annotation names to a two-tuple: the first element is the evaluated
        type or the original annotation if a `NameError` occurred, the second element is a boolean
        indicating if whether the evaluation succeeded.
    _FN)
r   reversed__mro__rt   pushtypes_namespaceitemsr\   try_eval_type	Exception	objru   hintsbaseannglobalnslocalnsnamevalues	            r"   get_model_type_hintsr   4  s      ;=E-K% #4(d# + ; ;Hg"yy{e??3'5&3E8W&Md #0x"IE$K  + $# &0 L	 % 5',end5 $#s0   7C B0C0C	 CC	CC	c               2   i }|xs
 t               }t        | j                        D ]b  }t        |      }|s|j	                  |      5  |j
                  \  }}|j                         D ]  \  }}t        |||      ||<    	 ddd       d |S # 1 sw Y   pxY w)zCollect annotations from a class, including those from parent classes.

    Args:
        obj: The class to inspect.
        ns_resolver: A namespace resolver instance to use. Defaults to an empty instance.
    N)r   rx   ry   rt   rz   r{   r|   	eval_typer   s	            r"   get_cls_type_hintsr   b  s     E-K% #4(d# + ; ;Hg"yy{e'xAd  + $# & L	 $#s   8BB	c                ^    t        |       } 	 t        | ||      dfS # t        $ r | dfcY S w xY w)a  Try evaluating the annotation using the provided namespaces.

    Args:
        value: The value to evaluate. If `None`, it will be replaced by `type[None]`. If an instance
            of `str`, it will be converted to a `ForwardRef`.
        localns: The global namespace to use during annotation evaluation.
        globalns: The local namespace to use during annotation evaluation.

    Returns:
        A two-tuple containing the possibly evaluated type and a boolean indicating
            whether the evaluation succeeded or not.
    TF)rh   eval_type_backport	NameErrorr   r   r   s      r"   r}   r}     s@    " % E!%7;TAA e|s    ,,c                2    t        |       } t        | ||      S )a  Evaluate the annotation using the provided namespaces.

    Args:
        value: The value to evaluate. If `None`, it will be replaced by `type[None]`. If an instance
            of `str`, it will be converted to a `ForwardRef`.
        localns: The global namespace to use during annotation evaluation.
        globalns: The local namespace to use during annotation evaluation.
    )rh   r   r   s      r"   r   r     s     % EeXw77r$   z?`eval_type_lenient` is deprecated, use `try_eval_type` instead.)categoryc                &    t        | ||      \  }}|S rM   )r}   )r   r   r   evrw   s        r"   eval_type_lenientr     s     %73EBIr$   c                   	 t        | |||      S # t        $ rp}dt        |      v r t        | t        j
                        sJ d| j                  d}t        j                  dk\  r|j                  |        t        |      |d}~wt        $ rU}dt                d}t        j                  dk\  r|j                  |        t        |j                  d    d	|       d}~ww xY w)
a  An enhanced version of `typing._eval_type` which will fall back to using the `eval_type_backport`
    package if it's installed to let older Python versions use newer typing constructs.

    Specifically, this transforms `X | Y` into `typing.Union[X, Y]` and `list[X]` into `typing.List[X]`
    (as well as all the types made generic in PEP 585) if the original syntax is not supported in the
    current Python version.

    This function will also display a helpful error if the value passed fails to evaluate.
    z"Unable to evaluate type annotation#Unable to evaluate type annotation .)r      NzIf you made use of an implicit recursive type alias (e.g. `MyType = list['MyType']), consider using PEP 695 type aliases instead. For more details, refer to the documentation: https://docs.pydantic.dev/z&/concepts/types/#named-recursive-typesr   
)_eval_type_backport	TypeErrorr9   r5   r6   r7   r8   rX   rl   add_noteRecursionErrorr   args)r   r   r   type_paramsemessages         r"   r   r     s    <"5(G[II ,/3q69 %!2!233378M8M7PPQRw&JJwG$!+ <))6(99_a 	
 w&JJw AFF1I;b	!:;;<s"    	C%A+BC%AC  C%c                   	 t        | |||      S # t        $ rk}t        | t        j                        rt        |      s 	 ddlm} n'# t        $ r t        d| j                  d      |w xY w || ||d      cY d }~S d }~ww xY w)Nr   )r   r   a  . If you are making use of the new typing syntax (unions using `|` since Python 3.10 or builtins subscripting since Python 3.9), you should either replace the use of new syntax with the existing `typing` constructs or install the `eval_type_backport` package.F)try_default)	
_eval_typer   r5   r6   r7   is_backport_fixable_errorr   ImportErrorr8   )r   r   r   r   r   r   s         r"   r   r     s    
%7K@@ 
5&"3"349RST9U	= 	5e6K6K5N OS S
 	 "	
 	

s2    	B&A? AA?$A++A?9B?Bc                    t         j                  dk\  r(t        j                  | |||      }|t	        d       }|S t         j                  dk\  rt        j                  | |||      S t        j                  | ||      S )Nr   )r   )r      )rX   rl   r6   r   type)r   r   r   r   	evaluateds        r"   r   r     s     7" %%#	
	 T
I			W	$  8W+
 	
   8W
 	
r$   c                d    t        |       }t        j                  dk  xr |j                  d      S )Nr   z#unsupported operand type(s) for |: )r9   rX   rl   r\   )r   msgs     r"   r   r     s+    
a&Cg%_#..9^*__r$   )include_keysr   r   c               z   	 t        | t              r| j                  j                  }n| j                  }|t        |       }d}|t        | dd      }i } |j                         D ]A  \  }}|||vr|t        }nt        |t              rt        |      }t        ||||      ||<   C |S # t        $ r i cY S w xY w)a  Return type hints for a function.

    This is similar to the `typing.get_type_hints` function, with a few differences:
    - Support `functools.partial` by using the underlying `func` attribute.
    - Do not wrap type annotation of a parameter with `Optional` if it has a default value of `None`
      (related bug: https://github.com/python/cpython/issues/90353, only fixed in 3.11+).
    N__type_params__ )r5   r   funcrk   AttributeErrorr   getattrr|   r   r9   rf   r   )	functionr   r   r   r   r   
type_hintsr   r   s	            r"   get_function_type_hintsr   %  s    h("--77K"22K
 #H-*.K h(92>J({((*e#L(@=Es#%e,E-eXwT
4 + /  	s   3B, ,B:9B:)r   	      )r   r   r   )re   c               .    t        j                  | |      S )a5  Wrapper for ForwardRef that accounts for the `is_class` argument missing in older versions.
        The `module` argument is omitted as it breaks <3.9.8, =3.10.0 and isn't used in the calls below.

        See https://github.com/python/cpython/pull/28560 for some background.
        The backport happened on 3.9.8, see:
        https://github.com/pydantic/pydantic/discussions/6244#discussioncomment-6275458,
        and on 3.10.1 for the 3.10 branch, see:
        https://github.com/pydantic/pydantic/issues/6912

        Implemented as EAFP with memory.
        )r6   r7   )rg   rd   re   s      r"   rf   rf   U  s    "   k22r$   c                   t        | dd      ri S t        | t              rNi }t        | j                        D ]  }|6t        t
        j                  j                  |j                  d      di       }n|}|j                  j                  di       }t        |t        j                        ri }|t        t        |            n|}||||}}|j                         D ]B  \  }	}
|
t        d      }
t        |
t              rt!        |
dd      }
t#        |
||      }
|
||	<   D  |sGt%        t&        d      r7|j                         D ci c]  \  }}|t'        j(                  |       c}}S |S |`t        | t        j*                        r| j                  }n4| }t%        |d	      r|j,                  }t%        |d	      rt        |d
i       }||}n||}t        | dd      }|*t        | t&        j.                        ri S t1        | d      t'        j2                  |       }t        |      }|j                         D ]w  \  }	}
|
t        d      }
t        |
t              r't!        |
t        | t        j*                         d      }
t#        |
||      }
|	|v r||	   t&        j4                  |
   }
|
||	<   y |r|S |j                         D ci c]  \  }}|t'        j(                  |       c}}S c c}}w c c}}w )a  Taken verbatim from python 3.10.8 unchanged, except:
        * type annotations of the function definition above.
        * prefixing `typing.` where appropriate
        * Use `_make_forward_ref` instead of `typing.ForwardRef` to handle the `is_class` argument.

        https://github.com/python/cpython/blob/aaaf5174241496afca7ce4d4584570190ff972fe/Lib/typing.py#L1773-L1875

        DO NOT CHANGE THIS METHOD UNLESS ABSOLUTELY NECESSARY.
        ======================================================

        Return type hints for an object.

        This is often the same as obj.__annotations__, but it handles
        forward references encoded as string literals, adds Optional[t] if a
        default value equal to None is set and recursively replaces all
        'Annotated[T, ...]' with 'T' (unless 'include_extras=True').

        The argument may be a module, class, method, or function. The annotations
        are returned as a dictionary. For classes, annotations include also
        inherited members.

        TypeError is raised if the argument is not of a type that can contain
        annotations, and an empty dictionary is returned if no annotations are
        present.

        BEWARE -- the behavior of globalns and localns is counterintuitive
        (unless you are familiar with how eval() and exec() work).  The
        search order is locals first, then globals.

        - If no dict arguments are passed, an attempt is made to use the
          globals from obj (or the respective module's globals for classes),
          and these are also used as the locals.  If the object does not appear
          to have globals, an empty dictionary is used.  For classes, the search
          order is globals first then locals.

        - If one dict argument is passed, it is used for both globals and
          locals.

        - If two dict arguments are passed, they specify globals and
          locals, respectively.
        __no_type_check__Nrq   rk   FTrc   _strip_annotations__wrapped____globals__z- is not a module, class, method, or function.)r   r5   r   rx   ry   rX   modulesrr   
__module__rq   rN   GetSetDescriptorTypedictvarsr|   r9   rf   r   rJ   r6   r   
ModuleTyper   _allowed_typesr   _get_defaultsOptional)r   r   r   include_extrasr   r   base_globalsr   base_localsr   r   ktnsobjdefaultss                  r"   get_type_hintsr   u  s   ` 3+T2Ic4 E -##*3;;??4??D+QS]_a#bL#+Lmm''(92>c5#=#=>C29/d4:.w?x'7 1<\+L#&99;KD%} $T
!%- 1%UUY Z.ulKPE"'E$K $/# .2 "gf6J&K !& -1 v0033 - 
 #u//0<<e]3!--E e]3"5-<"_G.5=#v445	3')V WXX'',U ;;=KD%}T
%% *$.sE4D4D$E E"
 'uh@ExHTN$:.E$K )  'ugY^YdYdYf,gYfQUQRTUQ0I0I!0L-LYf,gg[Z -hs   	 K3 K9)r    r   returnbool)r    r   r   z
Any | None)rU   intrV   r   r   dict[str, Any] | None)rg   r   r   r   )rs   	type[Any]r   dict[str, Any])r   ztype[BaseModel]ru   NsResolver | Noner   zdict[str, tuple[Any, bool]])r   r   ru   r   r   r   )NN)r   r   r   GlobalsNamespace | Noner   MappingNamespace | Noner   ztuple[Any, bool])r   r   r   r   r   r   r   r   )NNN)
r   r   r   r   r   r   r   ztuple[Any, ...] | Noner   r   )r   r   r   r   )
r   zCallable[..., Any]r   zset[str] | Noner   r   r   r   r   r   )T)rg   r   rd   r   re   r   r   ztyping.ForwardRef)NNF)
r   r   r   r   r   r   r   r   r   r   )S__doc__
__future__r   collections.abcr-   rerX   rN   r6   	functoolsr   r   r   r   r   typing_extensionsr	   r
   r   typing_inspectionr   typing_inspection.introspectionr   pydantic.versionr   _namespace_utilsr   r   r   r   rl   r   r   Ellipsisr   rm   pydanticr   	Annotatedr   r   r#   r(   r+   r0   r2   compiler:   r=   Finalr?   r@   rA   LiteralrB   rk   rD   rK   origin_is_unionrQ   rP   rO   rR   	UnionType_FinalrS   ra   rh   rt   r   r   r}   r   r   r   r   r   r   r   rf   r7   r   no_type_checkr   r$   r"   <module>r      s   u "  	 
    5 5  > > , ; * ^ ^gDzH>L2*w" !++	=R
Q

XX" rzzEF#L <<##	5  !%ht0DFWF_F_`dFef_ f D "F g&,&:&:E<N<N%OM?O&,&:&:E<N<NPUP_P_%`M?` ==S   345 =@$
7  &*+	+ #+ !	+b &*	 # 	@ )-'+% % 	6 )-'+88%8 %8 		8" E )-'+% % 			 )-'+*.	+<+<%+< %+< (	+<
 	+<` )-'+*.	

%
 %
 (	

 	
@ )-'+*.	

%
 %
 (	

 	
8` %)(,'+* * "* &	*
 %* *\ i7c.>.>#K#K !3 	333 	3
 
3( )) w**N
  +/)-$	{h{h'{h '{h 	{h
 
{h {hr$   