a
    lJhX                     @  s  U d Z ddlmZ ddlZddlZddl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mZ ddlmZmZmZmZ d	d
lmZ dZejdksejdk rdddddZndddddZdddddZddddddddddZed  Zd!ed"< e eeZ!d#ed$< G d%d& d&eZ"G d'd( d(e#Z$G d)d* d*e
Z%e%j&Z&ee%j& Z'd!ed+< G d,d- d-eZ(d.d/dd&dd-d0d1d2Z)dd3dd4d5d6d7Z*dd/ddd4d8d9d:Z+dS );zEHigh-level introspection utilities, used to inspect type annotations.    )annotationsN)	Generator)InitVar)EnumIntEnumauto)AnyLiteral
NamedTuplecast)	TypeAliasassert_neverget_args
get_origin   )typing_objects)AnnotationSourceForbiddenQualifierInspectedAnnotation	Qualifierget_literal_valuesinspect_annotationis_union_origin)      )r   
   r   bool)objreturnc                C  s
   t | S a  Return whether the provided origin is the union form.

        ```pycon
        >>> is_union_origin(typing.Union)
        True
        >>> is_union_origin(get_origin(int | str))
        True
        >>> is_union_origin(types.UnionType)
        True
        ```

        !!! note
            Since Python 3.14, both `Union[<t1>, <t2>, ...]` and `<t1> | <t2> | ...` forms create instances
            of the same [`typing.Union`][] class. As such, it is recommended to not use this function
            anymore (provided that you only support Python 3.14 or greater), and instead use the
            [`typing_objects.is_union()`][typing_inspection.typing_objects.is_union] function directly:

            ```python
            from typing import Union, get_origin

            from typing_inspection import typing_objects

            typ = int | str  # Or Union[int, str]
            origin = get_origin(typ)
            if typing_objects.is_union(origin):
                ...
            ```
        )r   is_unionr    r"   Q/var/www/shaz/venv/lib/python3.9/site-packages/typing_inspection/introspection.pyr      s    r   c                C  s   t | p| tju S r   )r   r    types	UnionTyper!   r"   r"   r#   r   >   s    None)valuer   c                C  s4   t | ttttttjfs0| tjur0t|  ddS )zCType check the provided literal value against the legal parameters.zK is not a valid literal value, must be one of: int, bytes, str, Enum, None.N)	
isinstanceintbytesstrr   r   r   NoneType	TypeError)r'   r"   r"   r#   _literal_type_check^   s
    r.   Feager
type_checkunpack_type_aliasesz#Literal['skip', 'lenient', 'eager']zGenerator[Any])
annotationr1   r2   r   c         	   	   c  s^  |dkrPd}| j D ]8}|r"t| |du s4|tju rD|s>dV  d}q|V  qn
g }| j D ]}t|rz
|j}W n: ty   |dkr |rt| ||t|f Y n$0 t	|||d}|
dd |D  qZ|rt| |tju r|dtjf qZ||t|f qZzt|}W n( tyD   d	d |D E dH  Y n0 d
d |D E dH  dS )a=  Yield the values contained in the provided [`Literal`][typing.Literal] [special form][].

    Args:
        annotation: The [`Literal`][typing.Literal] [special form][] to unpack.
        type_check: Whether to check if the literal values are [legal parameters][literal-legal-parameters].
            Raises a [`TypeError`][] otherwise.
        unpack_type_aliases: What to do when encountering [PEP 695](https://peps.python.org/pep-0695/)
            [type aliases][type-aliases]. Can be one of:

            - `'skip'`: Do not try to parse type aliases. Note that this can lead to incorrect results:
              ```pycon
              >>> type MyAlias = Literal[1, 2]
              >>> list(get_literal_values(Literal[MyAlias, 3], unpack_type_aliases="skip"))
              [MyAlias, 3]
              ```

            - `'lenient'`: Try to parse type aliases, and fallback to `'skip'` if the type alias can't be inspected
              (because of an undefined forward reference).

            - `'eager'`: Parse type aliases and raise any encountered [`NameError`][] exceptions (the default):
              ```pycon
              >>> type MyAlias = Literal[1, 2]
              >>> list(get_literal_values(Literal[MyAlias, 3], unpack_type_aliases="eager"))
              [1, 2, 3]
              ```

    Note:
        While `None` is [equivalent to][none] `type(None)`, the runtime implementation of [`Literal`][typing.Literal]
        does not de-duplicate them. This function makes sure this de-duplication is applied:

        ```pycon
        >>> list(get_literal_values(Literal[NoneType, None]))
        [None]
        ```

    Example:
        ```pycon
        >>> type Ints = Literal[1, 2]
        >>> list(get_literal_values(Literal[1, Ints], unpack_type_alias="skip"))
        ["a", Ints]
        >>> list(get_literal_values(Literal[1, Ints]))
        [1, 2]
        >>> list(get_literal_values(Literal[1.0], type_check=True))
        Traceback (most recent call last):
        ...
        TypeError: 1.0 is not a valid literal value, must be one of: int, bytes, str, Enum, None.
        ```
    skipFNTr/   r0   c                 s  s   | ]}|t |fV  qd S N)type).0ar"   r"   r#   	<genexpr>       z%get_literal_values.<locals>.<genexpr>c                 s  s   | ]\}}|V  qd S r5   r"   r7   p_r"   r"   r#   r9      r:   c                 s  s   | ]\}}|V  qd S r5   r"   r;   r"   r"   r#   r9      r:   )__args__r.   r   r,   is_typealiastype	__value__	NameErrorappendr6   r   extenddictfromkeysr-   )	r3   r1   r2   Z	_has_noneargZvalues_and_typeZalias_valueZsub_argsdctr"   r"   r#   r   g   sF    :




r   )requirednot_required	read_only	class_varinit_varfinalr   r   set[Qualifier]_all_qualifiersc                   @  sR   e Zd ZdZe Ze Ze Ze Ze Z	e Z
e Ze ZeddddZdS )r   zThe source of an annotation, e.g. a class or a function.

    Depending on the source, different [type qualifiers][type qualifier] may be (dis)allowed.
    rN   r   c                 C  sz   | t ju rdhS | t ju r"ddhS | t ju r4h dS | t ju rFh dS | t jt jt jfv r`t S | t j	u rnt
S t|  dS )zIThe allowed [type qualifiers][type qualifier] for this annotation source.rM   rK   >   rM   rL   rK   >   rH   rJ   rI   N)r   ASSIGNMENT_OR_VARIABLECLASS	DATACLASS
TYPED_DICTNAMED_TUPLEFUNCTIONBAREsetANYrO   r   selfr"   r"   r#   allowed_qualifiers<  s    




z#AnnotationSource.allowed_qualifiersN)__name__
__module____qualname____doc__r   rQ   rR   rS   rT   rU   rV   rY   rW   propertyr\   r"   r"   r"   r#   r      s   r   c                   @  s*   e Zd ZU dZded< dddddZdS )	r   z-The provided [type qualifier][] is forbidden.r   	qualifierr&   )rb   r   c                C  s
   || _ d S r5   )rb   )r[   rb   r"   r"   r#   __init__V  s    zForbiddenQualifier.__init__N)r]   r^   r_   r`   __annotations__rc   r"   r"   r"   r#   r   P  s   
r   c                   @  s.   e Zd Ze ZddddZddddZdS )_UnknownTypeEnumr+   rP   c                 C  s   dS )NUNKNOWNr"   rZ   r"   r"   r#   __str__]  s    z_UnknownTypeEnum.__str__c                 C  s   dS )Nz	<UNKNOWN>r"   rZ   r"   r"   r#   __repr__`  s    z_UnknownTypeEnum.__repr__N)r]   r^   r_   r   rf   rg   rh   r"   r"   r"   r#   re   Z  s   re   _UnkownTypec                   @  s*   e Zd ZU dZded< ded< ded< dS )	r   z'The result of the inspected annotation.zAny | _UnkownTyper6   rN   
qualifiersz	list[Any]metadataN)r]   r^   r_   r`   rd   r"   r"   r"   r#   r   k  s
   
r   r4   r2   )r3   annotation_sourcer2   r   c               C  s
  |j }t }g }t| |d\} }|r.|| }qt| }|dur<t|rpd|vrZtd|d | jd } nt	|rd|vrtd|d | jd } nt
|rd|vrtd|d | jd } njt|rd|vrtd|d | jd } n8t|rxd|vr td|d | jd } nqxqt| trxd	|vrZtd	|d	 tt| j} qqxqt	| rd|vrtd|d t} nXt| rd|vrtd|d t} n*| tu rd	|vrtd	|d	 t} t| ||S )
a
  Inspect an [annotation expression][], extracting any [type qualifier][] and metadata.

    An [annotation expression][] is a [type expression][] optionally surrounded by one or more
    [type qualifiers][type qualifier] or by [`Annotated`][typing.Annotated]. This function will:

    - Unwrap the type expression, keeping track of the type qualifiers.
    - Unwrap [`Annotated`][typing.Annotated] forms, keeping track of the annotated metadata.

    Args:
        annotation: The annotation expression to be inspected.
        annotation_source: The source of the annotation. Depending on the source (e.g. a class), different type
            qualifiers may be (dis)allowed. To allow any type qualifier, use
            [`AnnotationSource.ANY`][typing_inspection.introspection.AnnotationSource.ANY].
        unpack_type_aliases: What to do when encountering [PEP 695](https://peps.python.org/pep-0695/)
            [type aliases][type-aliases]. Can be one of:

            - `'skip'`: Do not try to parse type aliases (the default):
              ```pycon
              >>> type MyInt = Annotated[int, 'meta']
              >>> inspect_annotation(MyInt, annotation_source=AnnotationSource.BARE, unpack_type_aliases='skip')
              InspectedAnnotation(type=MyInt, qualifiers={}, metadata=[])
              ```

            - `'lenient'`: Try to parse type aliases, and fallback to `'skip'` if the type alias
              can't be inspected (because of an undefined forward reference):
              ```pycon
              >>> type MyInt = Annotated[Undefined, 'meta']
              >>> inspect_annotation(MyInt, annotation_source=AnnotationSource.BARE, unpack_type_aliases='lenient')
              InspectedAnnotation(type=MyInt, qualifiers={}, metadata=[])
              >>> Undefined = int
              >>> inspect_annotation(MyInt, annotation_source=AnnotationSource.BARE, unpack_type_aliases='lenient')
              InspectedAnnotation(type=int, qualifiers={}, metadata=['meta'])
              ```

            - `'eager'`: Parse type aliases and raise any encountered [`NameError`][] exceptions.

    Returns:
        The result of the inspected annotation, where the type expression, used qualifiers and metadata is stored.

    Example:
        ```pycon
        >>> inspect_annotation(
        ...     Final[Annotated[ClassVar[Annotated[int, 'meta_1']], 'meta_2']],
        ...     annotation_source=AnnotationSource.CLASS,
        ... )
        ...
        InspectedAnnotation(type=int, qualifiers={'class_var', 'final'}, metadata=['meta_1', 'meta_2'])
        ```
    rl   NrK   r   rM   rH   rI   rJ   rL   )r\   rX   _unpack_annotatedr   r   Zis_classvarr   addr>   Zis_finalZis_requiredZis_notrequiredZis_readonlyr(   r   r   r   r6   rf   r   )r3   rm   r2   r\   rj   rk   _metaoriginr"   r"   r#   r     sr    8


















r   zLiteral['lenient', 'eager']ztuple[Any, list[Any]])r3   r2   check_annotatedr   c           	      C  s(  t | }|rHt|rH| j}t| j}t||dd\}}|| }||fS t| rz
| j}W n t	yx   |dkrt Y n(0 t||dd\}}|r||fS | g fS n~t|r z
|j}W n t	y   |dkrЂ Y nL0 z|| j
 }W n ty   Y n0 t||dd\}}|r||fS | g fS | g fS )NFr2   rr   r/   T)r   r   is_annotated
__origin__list__metadata___unpack_annotated_innerr?   r@   rA   r>   r-   )	r3   r2   rr   rq   annotated_typerk   Zsub_metar'   typr"   r"   r#   rx     sL    







rx   )r3   r2   r   c               C  s<   |dkr.t t| r&| jt| jfS | g fS t| |ddS )Nr4   Trs   )r   rt   r   ru   rv   rw   rx   )r3   r2   r"   r"   r#   rn   B  s
    rn   ),r`   
__future__r   sysr$   collections.abcr   dataclassesr   enumr   r   r   typingr   r	   r
   r   typing_extensionsr   r   r   r    r   __all__version_infor   r.   r   r   rd   rX   rO   r   	Exceptionr   re   rf   ri   r   r   rx   rn   r"   r"   r"   r#   <module>   s<   
" pq

|D