a
    “˜ëj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s¢ejdk r´d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"   ú^/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/typing_inspection/introspection.pyr      s    r   c                C  s   t  | ¡p| tju S r   )r   r    ÚtypesZ	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])Ú
annotationr0   r1   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 |¡rÒz
|j}W n: ty¬   |dkrŠ‚ |r–t|ƒ | |t|ƒf¡ Y n$0 t	|||d�}| 
dd„ |D ƒ¡ qZ|rÞt|ƒ |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.   r/   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 r4   r"   ©r6   ÚpÚ_r"   r"   r#   r8   Ò   r9   c                 s  s   | ]\}}|V  qd S r4   r"   r:   r"   r"   r#   r8   Ô   r9   )Ú__args__r-   r   r+   Úis_typealiastypeÚ	__value__Ú	NameErrorÚappendr5   r   ÚextendÚdictÚfromkeysr,   )	r2   r0   r1   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   zœThe source of an annotation, e.g. a class or a function.

    Depending on the source, different [type qualifiers][type qualifier] may be (dis)allowed.
    rM   ©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.rL   rJ   >   rJ   rK   rL   >   rG   rI   rH   N)r   ÚASSIGNMENT_OR_VARIABLEÚCLASSÚ	DATACLASSÚ
TYPED_DICTÚNAMED_TUPLEÚFUNCTIONÚBAREÚsetÚANYrN   r   ©Úselfr"   r"   r#   Úallowed_qualifiers<  s    




z#AnnotationSource.allowed_qualifiersN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   rP   rQ   rR   rS   rT   rU   rX   rV   Ú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%   )ra   r   c                C  s
   || _ d S r4   )ra   )rZ   ra   r"   r"   r#   Ú__init__V  s    zForbiddenQualifier.__init__N)r\   r]   r^   r_   Ú__annotations__rb   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*   rO   c                 C  s   dS )NÚUNKNOWNr"   rY   r"   r"   r#   Ú__str__]  s    z_UnknownTypeEnum.__str__c                 C  s   dS )Nz	<UNKNOWN>r"   rY   r"   r"   r#   Ú__repr__`  s    z_UnknownTypeEnum.__repr__N)r\   r]   r^   r   re   rf   rg   r"   r"   r"   r#   rd   Z  s   rd   Ú_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 | _UnkownTyper5   rM   Ú
qualifiersz	list[Any]ÚmetadataN)r\   r]   r^   r_   rc   r"   r"   r"   r#   r   k  s
   
r   r3   ©r1   )r2   Úannotation_sourcer1   r   c               C  s
  |j }tƒ }g }t| |d�\} }|r.|| }qt| ƒ}|du�r<t |¡rpd|vrZtdƒ‚| d¡ | jd } nÊt 	|¡r d|vrŠtdƒ‚| d¡ | jd } nšt 
|¡rÐd|vrºtdƒ‚| d¡ | jd } njt |¡�rd|vrìt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 	| ¡�r¦d|v�r–tdƒ‚| d¡ t} nXt | ¡�rÔd|v�rÄtdƒ‚| d¡ t} n*| tu �rþd	|v�rðt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'])
        ```
    rk   NrJ   r   rL   rG   rH   rI   rK   )r[   rW   Ú_unpack_annotatedr   r   Zis_classvarr   Úaddr=   Úis_finalZis_requiredZis_notrequiredZis_readonlyr'   r   r   r   r5   re   r   )r2   rl   r1   r[   ri   rj   Z_metaÚoriginr"   r"   r#   r   ƒ  sr    8


















r   zLiteral['lenient', 'eager']ztuple[Any, list[Any]])r2   r1   Úcheck_annotatedr   c           	      C  s(  t | ƒ}|rHt |¡rH| j}t| jƒ}t||dd�\}}|| }||fS t | ¡r¢z
| 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©r1   rq   r.   T)r   r   Úis_annotatedÚ
__origin__ÚlistÚ__metadata__Ú_unpack_annotated_innerr>   r?   r@   r=   r,   )	r2   r1   rq   rp   Úannotated_typerj   Zsub_metar&   Útypr"   r"   r#   rw   ÿ  sL    
ÿ


ÿ


ÿ
rw   )r2   r1   r   c               C  s<   |dkr.t  t| ƒ¡r&| jt| jƒfS | g fS t| |dd�S )Nr3   Trr   )r   rs   r   rt   ru   rv   rw   )r2   r1   r"   r"   r#   rm   B  s
    rm   ),r_   Ú
__future__r   Úsysr$   Úcollections.abcr   Zdataclassesr   Úenumr   r   r   Útypingr   r	   r
   r   Ztyping_extensionsr   r   r   r   Ú r   Ú__all__Úversion_infor   r-   r   r   rc   rW   rN   r   Ú	Exceptionr   rd   re   rh   r   r   rw   rm   r"   r"   r"   r#   Ú<module>   s<   
" ûpq

û|Dÿ