U
    hmn                     @   s0  d Z ddlZddlZddlZddlZddlmZ dejdd   krNdk r`n nddlmZ	 nZejdd dkrzddlmZ	 W q e
k
r   ddlmZ	 Y qX nddlmZ eeZ	ejdd dkZerddlZd	Zd	Zd	Zd	Zd
ZerfddlmZmZmZmZmZmZmZmZmZ ddlmZmZ ejdd dkr\ddlm Z  ee ej!fZ"nefZ"n`ddlmZm#Z#mZmZm$Z$mZm%Z%m&Z& zddlm'Z'm(Z( W n& e
k
r   eeZ'd
Zd	ZY nX zddlm)Z) W nB e
k
r   zddlm)Z) W n e
k
r   d
ZY nX Y nX zddlmZ W nB e
k
rp   zddlmZ W n e
k
rj   d
ZY nX Y nX zddlmZ W nB e
k
r   zddlmZ W n e
k
r   d
ZY nX Y nX dd Z*dd Z+dd Z,dd Z-dd Z.dd Z/z
ej0Z1W n e2k
r   dZ1Y nX d d! Z3ehZ4e5ed"rBe46ej d#d$ Z7d%d& Z8d'd( Z9d)d* Z:d+d, Z;d-d. Z<d/d0 Z=d1d2 Z>d3d4 Z?d5d6 Z@d[d7d8ZAd9d: ZBd;d< ZCd=d> ZDd?d@ ZEdAdB ZFdCdD ZGdEdF ZHdGdH ZId\dIdJZJd]dKdLZKd^dMdNZLd_dOdPZMdQdR ZNdSdT ZOdUdV ZPdWdX ZQdYdZ ZRdS )`zDefines experimental API for runtime inspection of types defined
in the standard "typing" module.

Example usage::
    from typing_inspect import is_generic_type
    N)_TypedDictMeta)      r   r   )r   	      )	TypedDict)r      r   TF)	GenericCallableUnionTypeVarClassVarTuple_GenericAlias
ForwardRefNewType)FinalLiteral)r   r   r   )_SpecialGenericAlias)r
   CallableMetar   r   	TupleMetar   GenericMeta_ForwardRef)_Union	_ClassVar)_Final)r   )r   c                 C   s4   t | tstt| dr| jS | jdk	r0| j} q| S )z@This function exists for compatibility with old typing versions._gorgN)
isinstancer   AssertionErrorhasattrr   
__origin__cls r#   2/tmp/pip-unpacked-wheel-ixaamrzm/typing_inspect.pyr   \   s    

r   c                 C   sR   t r8t| trt| tp6t| to6| jttt	t
jjfkS t| toPt| ttf S )a  Test if the given type is a generic type. This includes Generic itself, but
    excludes special typing constructs such as Union, Tuple, Callable, ClassVar.
    Examples::

        is_generic_type(int) == False
        is_generic_type(Union[int, str]) == False
        is_generic_type(Union[int, T]) == False
        is_generic_type(ClassVar[List[int]]) == False
        is_generic_type(Callable[..., T]) == False

        is_generic_type(Generic) == True
        is_generic_type(Generic[T]) == True
        is_generic_type(Iterable[int]) == True
        is_generic_type(Mapping) == True
        is_generic_type(MutableMapping[T, List[int]]) == True
        is_generic_type(Sequence[Union[str, bytes]]) == True
    )
NEW_TYPINGr   type
issubclassr	   typingGenericAliasr    r   tupler   collectionsabcr
   r   r   r   tpr#   r#   r$   is_generic_typef   s    

r.   c                 C   sR   t rF| tkpDt| tr$| jtjjkpDt| toDt| t	oDt| tjjS t| t
kS )a  Test if the type is a generic callable type, including subclasses
    excluding non-generic types and callables.
    Examples::

        is_callable_type(int) == False
        is_callable_type(type) == False
        is_callable_type(Callable) == True
        is_callable_type(Callable[..., int]) == True
        is_callable_type(Callable[[int, int], Iterable[str]]) == True
        class MyClass(Callable[[int], int]):
            ...
        is_callable_type(MyClass) == True

    For more general tests use callable(), for more precise test
    (excluding subclasses) use::

        get_origin(tp) is collections.abc.Callable  # Callable prior to Python 3.7
    )r%   r
   r   r(   r    r*   r+   r&   r'   r	   r   r,   r#   r#   r$   is_callable_type   s    r/   c                 C   sJ   t r>| tkp<t| tr | jtkp<t| to<t| to<t| tS t| t	kS )a   Test if the type is a generic tuple type, including subclasses excluding
    non-generic classes.
    Examples::

        is_tuple_type(int) == False
        is_tuple_type(tuple) == False
        is_tuple_type(Tuple) == True
        is_tuple_type(Tuple[str, int]) == True
        class MyClass(Tuple[str, int]):
            ...
        is_tuple_type(MyClass) == True

    For more general tests use issubclass(..., tuple), for more precise test
    (excluding subclasses) use::

        get_origin(tp) is tuple  # Tuple prior to Python 3.7
    )
r%   r   r   r(   r    r)   r&   r'   r	   r   r,   r#   r#   r$   is_tuple_type   s    r0   c                 C   s:   | t dkrdS t| r2tdd t| ddD S dS dS )a  Test if the type is type(None), or is a direct union with it, such as Optional[T].

    NOTE: this method inspects nested `Union` arguments but not `TypeVar` definition
    bounds and constraints. So it will return `False` if
     - `tp` is a `TypeVar` bound, or constrained to, an optional type
     - `tp` is a `Union` to a `TypeVar` bound or constrained to an optional type,
     - `tp` refers to a *nested* `Union` containing an optional type or one of the above.

    Users wishing to check for optionality in types relying on type variables might wish
    to use this method in combination with `get_constraints` and `get_bound`
    NTc                 s   s   | ]}t |V  qd S N)is_optional_type).0ttr#   r#   r$   	<genexpr>   s     z#is_optional_type.<locals>.<genexpr>)evaluateF)r&   is_union_typeanyget_argsr,   r#   r#   r$   r2      s
    r2   c                 C   s0   t r | tkpt| to| jtkS to.t| tkS )zTest if the type is a final type. Examples::

        is_final_type(int) == False
        is_final_type(Final) == True
        is_final_type(Final[int]) == True
    )r%   r   r   r(   r    
WITH_FINALr&   r   r,   r#   r#   r$   is_final_type   s
    r;   c                 C   s:   t r.| tkp,t| tr | jtkp,to,t| tS t| tkS )a)  Test if the type is a union type. Examples::

        is_union_type(int) == False
        is_union_type(Union) == True
        is_union_type(Union[int, int]) == False
        is_union_type(Union[T, int]) == True
        is_union_type(int | int) == False
        is_union_type(T | int) == True
    )r%   r   r   r(   r    MaybeUnionTyper&   r   r,   r#   r#   r$   r7      s    
r7   r   c                 C   s4   t r | tkpt| to| jtkS to2t| ttkS r1   )r%   LITERALSr   r(   r    WITH_LITERALr&   r   r,   r#   r#   r$   is_literal_type   s
    r?   c                 C   s   t | tkS )zTest if the type represents a type variable. Examples::

        is_typevar(int) == False
        is_typevar(T) == True
        is_typevar(Union[T, int]) == False
    )r&   r   r,   r#   r#   r$   
is_typevar   s    r@   c                 C   s8   t r | tkpt| to| jtkS tr0t| tkS dS dS )zTest if the type represents a class variable. Examples::

        is_classvar(int) == False
        is_classvar(ClassVar) == True
        is_classvar(ClassVar[int]) == True
        is_classvar(ClassVar[List[T]]) == True
    FN)r%   r   r   r(   r    WITH_CLASSVARr&   r   r,   r#   r#   r$   is_classvar  s    rB   c                 C   s   t sdS tjdd dkrDtjjdkrD| ttjfkpBt| ttjfS tjdd dkrzt| tj}W n tk
rz   Y n
X |r|S | ttjfkpt| dddk	ot| dd	d
ko| j	dkS | tkpt| dddk	o| j	dkS dS )zTests if the type represents a distinct type. Examples::

        is_new_type(int) == False
        is_new_type(NewType) == True
        is_new_type(NewType('Age', int)) == True
        is_new_type(NewType('Scores', List[Dict[str, float]])) == True
    FNr   )r   
   r   beta)r   r   r   __supertype____qualname__ zNewType.<locals>.new_type)typingtyping_extensions)
WITH_NEWTYPEsysversion_inforeleaselevelr   rI   r   	TypeErrorgetattr
__module__)r-   resr#   r#   r$   is_new_type  s.    rR   c                 C   s   t st| tS t| tS )zTests if the type is a :class:`typing.ForwardRef`. Examples::

        u = Union["Milk", Way]
        args = get_args(u)
        is_forward_ref(args[0]) == True
        is_forward_ref(args[1]) == False
    )r%   r   r   r   r,   r#   r#   r$   is_forward_ref6  s    
rS   c                 C   s:   t rtdt }t| d|}||kr*dS |dkr6| S |S )a  Get the last base of (multiply) subscripted type. Supports generic types,
    Union, Callable, and Tuple. Returns None for unsupported types.
    Examples::

        get_last_origin(int) == None
        get_last_origin(ClassVar[int]) == None
        get_last_origin(Generic[T]) == Generic
        get_last_origin(Union[T, int][str]) == Union[T, int]
        get_last_origin(List[Tuple[T, T]][int]) == List[Tuple[T, T]]
        get_last_origin(List) == List
    zEThis function is only supported in Python 3.6, use get_origin insteadr    N)r%   
ValueErrorobjectrO   )r-   sentineloriginr#   r#   r$   get_last_originC  s    rX   c                 C   sz   t r2t| tr"| jtk	r| jS dS | tkr.tS dS t| trDt| S t| rPt	S t
| r\tS t| rvt rr| jpp| S tS dS )a  Get the unsubscripted version of a type. Supports generic types, Union,
    Callable, and Tuple. Returns None for unsupported types. Examples::

        get_origin(int) == None
        get_origin(ClassVar[int]) == None
        get_origin(Generic) == Generic
        get_origin(Generic[T]) == Generic
        get_origin(Union[T, int]) == Union
        get_origin(List[Tuple[T, T]][int]) == list  # List prior to Python 3.7
    N)r%   r   r(   r    r   r	   r   r   r7   r   r0   r   r?   r   r,   r#   r#   r$   
get_origin[  s"    


rY   c                 C   s  t rt| r@g }| jdk	r"| jndD ]}|t|7 }q&t|S t| rzg }| jdk	r\| jndD ]}|t|7 }q`t|S t| rg }| j}|dkrdS |D ]\}t|rt	|n|fD ]@}t
|rt|tstd| |dkrg }||kr|| qq|dk	rt|S dS ndS ntrft| tr8t| dsZt| tr`t| tr`| tk	r`| jS dS nBt| st| st| st| r| jdk	r| jS dS dS dS )a>  Return type parameters of a parameterizable type as a tuple
    in lexicographic order. Parameterizable types are generic types,
    unions, tuple types and callable types. Examples::

        get_parameters(int) == ()
        get_parameters(Generic) == ()
        get_parameters(Union) == ()
        get_parameters(List[int]) == ()

        get_parameters(Generic[T]) == (T,)
        get_parameters(Tuple[List[T], List[S_co]]) == (T, S_co)
        get_parameters(Union[S_co, Tuple[T, T]][int, U]) == (U,)
        get_parameters(Mapping[T, Tuple[S_co, T]]) == (T, S_co)
    Nr#   zKCannot inherit from a generic class parameterized with non-type-variable %s__parameters__)LEGACY_TYPINGr7   __union_params__get_parametersr)   r0   __tuple_params__r.   rZ   r9   _has_type_varr   r   rN   appendr%   r(   r   r&   r'   r	   r/   )r-   paramsargZbase_paramsZbp_Zbpr#   r#   r$   r]   z  sn    

r]   c                 C   sD  t rtdn0t| r.| jdk	r*| jfS dS t| rz$| jdk	rXt| jdkrX| jW S W n tk
rn   Y nX | jdk	r| jS dS t	| rz| jdk	r| jndW S  tk
r   | j
dk	r| j
nd Y S X nrt| r| jdk	r| jS dS t| r<z| jdk	r| jndW S  tk
r8   | jdk	r0| jnd Y S X ndS dS )a  Get last arguments of (multiply) subscripted type.
       Parameters for Callable are flattened. Examples::

        get_last_args(int) == ()
        get_last_args(Union) == ()
        get_last_args(ClassVar[int]) == (int,)
        get_last_args(Union[T, int]) == (T, int)
        get_last_args(Iterable[Tuple[T, S]][int, T]) == (int, T)
        get_last_args(Callable[[T], int]) == (T, int)
        get_last_args(Callable[[], int]) == (int,)
    zCThis function is only supported in Python 3.6, use get_args insteadNr#   r   )r%   rT   rB   __type__r.   __args__lenAttributeErrorrZ   r7   r\   r/   r0   r^   r,   r#   r#   r$   get_last_args  s0    
rg   c              
   C   s   g }| D ]}t |ts"|| qt|d rt|dd }t|dkrb|tg |d f  q|d tkr|td|d f  q|tt|dd |d f  q|t	|d 
|d t|dd  qt|S )zInternal helper for get_args.r      Nr   .)r   r)   r`   r/   
_eval_argsre   r
   Ellipsislistr&   __getitem__)argsrQ   rb   Zcallable_argsr#   r#   r$   rj     s    
$,rj   c                 C   s  t r|dk	r|stdt| trjt| drj| j}t| tjj	krf|d t
k	rft|dd |d f}|S tr~t| tr~| jS dS t| st| r| jdk	r| jfS dS t| r| jpdS t| st| st| st| rz|  }W nX tk
r@   t| rt| }n.t| r"t| }nt| r6t| }nY dS Y nX t|trt|dkr|sn|dd S t|dd }t| t	kr|d t
k	rt|dd |d f}|S dS )a  Get type arguments with all substitutions performed. For unions,
    basic simplifications used by Union constructor are performed.
    On versions prior to 3.7 if `evaluate` is False (default),
    report result as nested tuple, this matches
    the internal representation of types. If `evaluate` is True
    (or if Python version is 3.7 or greater), then all
    type parameters are applied (this could be time and memory expensive).
    Examples::

        get_args(int) == ()
        get_args(Union[int, Union[T, int], str][int]) == (int, str)
        get_args(Union[int, Tuple[T, int]][str]) == (int, (Tuple, str, int))

        get_args(Union[int, Tuple[T, int]][str], evaluate=True) ==                  (int, Tuple[str, int])
        get_args(Dict[int, Tuple[T, T]][Optional[int]], evaluate=True) ==                  (int, Tuple[Optional[int], Optional[int]])
        get_args(Callable[[], T][int], evaluate=True) == ([], int,)
    Nz*evaluate can only be True in Python >= 3.7rd   r   ri   r#   rh   )r%   rT   r   r(   r   rd   rY   r*   r+   r
   rk   rl   r<   rB   r;   rc   r?   Z
__values__r.   r7   r/   r0   
_subs_treerf   _union_subs_tree_generic_subs_tree_tuple_subs_treer)   re   rj   )r-   r6   rQ   treer#   r#   r$   r9     sR    






r9   c                 C   s(   t | rt| ddS tdt|  dS )zReturn the type bound to a `TypeVar` if any.

    It the type is not a `TypeVar`, a `TypeError` is raised.
    Examples::

        get_bound(TypeVar('T')) == None
        get_bound(TypeVar('T', bound=int)) == int
    	__bound__Ntype is not a `TypeVar`: r@   rO   rN   strr,   r#   r#   r$   	get_boundA  s    
rx   c                 C   s(   t | rt| ddS tdt|  dS )zReturns the constraints of a `TypeVar` if any.

    It the type is not a `TypeVar`, a `TypeError` is raised
    Examples::

        get_constraints(TypeVar('T')) == ()
        get_constraints(TypeVar('T', int, str)) == (int, str)
    __constraints__r#   ru   Nrv   r,   r#   r#   r$   get_constraintsQ  s    
rz   c                 C   s    t | dd}|dk	r|S t| S )a6  Get the generic type of an object if possible, or runtime class otherwise.
    Examples::

        class Node(Generic[T]):
            ...
        type(Node[int]()) == Node
        get_generic_type(Node[int]()) == Node[int]
        get_generic_type(Node[T]()) == Node[T]
        get_generic_type(1) == int
    __orig_class__N)rO   r&   )objZgen_typer#   r#   r$   get_generic_typea  s    r}   c                 C   s(   t rtdd | jD S t| ddS dS )a  Get generic base types of a type or empty tuple if not possible.
    Example::

        class MyClass(List[int], Mapping[str, List[int]]):
            ...
        MyClass.__bases__ == (List, Mapping)
        get_generic_bases(MyClass) == (List[int], Mapping[str, List[int]])
    c                 s   s   | ]}t |tr|V  qd S r1   )r   r   r3   tr#   r#   r$   r5   {  s     
 z$get_generic_bases.<locals>.<genexpr>__orig_bases__r#   N)r[   r)   	__bases__rO   r,   r#   r#   r$   get_generic_basesq  s    	r   c                 C   s   t | ttfr| j S dS )a  If td is a TypedDict class, return a dictionary mapping the typed keys to types.
    Otherwise, return None. Examples::

        class TD(TypedDict):
            x: int
            y: int
        class Other(dict):
            x: int
            y: int

        typed_dict_keys(TD) == {'x': int, 'y': int}
        typed_dict_keys(dict) == None
        typed_dict_keys(Other) == None
    N)r   _TypedDictMeta_Mypy_TypedDictMeta_TE__annotations__copy)tdr#   r#   r$   typed_dict_keys  s    
r   c                 C   s   t | r| jS dS )a  
    If fr is a ForwardRef, return the string representation of the forward reference.
    Otherwise return None. Examples::

        tp = List["FRef"]
        fr = get_args(tp)[0]
        get_forward_arg(fr) == "FRef"
        get_forward_arg(tp) == None
    N)rS   __forward_arg__)frr#   r#   r$   get_forward_arg  s    
r   c                 C   s|   |dkrg }t | r t| ||S t| r4t| ||S t| rHt| ||S t| trxt|D ]\}}| |krZ||   S qZ| S )zbackport of _replace_argN)	r7   rp   r0   rr   r.   rq   r   r   	enumerate)rb   tvarsrn   itvarr#   r#   r$   _replace_arg  s    
r   c                    s  g }| D ]\}t |tr$||j qt |trZt|dkrZ|d tkrZ||dd  q|| qt| t t|k rg }|D ] }| kr||  	| q|} rt
 t| |D ]6t tsqtfdd h D rĈ 	 qt fdd|D S )z backport of _remove_dups_flattenr   rh   Nc                 3   sB   | ]:}t |trt|d k	st |tst |to8t |V  qd S r1   )r   r   rY   r   r&   r'   )r3   t2)t1r#   r$   r5     s
   

z'_remove_dups_flatten.<locals>.<genexpr>c                 3   s   | ]}| kr|V  qd S r1   r#   r~   )
all_paramsr#   r$   r5     s      )r   r   extendr\   r)   re   r   r`   setremover   r&   r8   )
parametersra   p
new_paramsr   r#   )r   r   r$   _remove_dups_flatten  s2    
"

r   c                 C   s   dd }|| }|dkr,t | s,t| s,| S g }||dk	rP|| ||}q0g }dd }|| D ]}|t||| qd|D ]0}	g }
||	D ]}|
t|t|	| q|
}q|S )z;backport of typing._subs_tree, adapted for legacy versions c                 S   s$   z| j W S  tk
r   Y d S X d S r1   )r    rf   r!   r#   r#   r$   _get_origin  s    z_subs_tree.<locals>._get_originNc                 S   sT   t | r| j}n4t| r | j}n$z
| j}W n tk
rB   d}Y nX |d k	rP|S dS )Nr#   )r7   r\   r0   r^   rd   rf   )r"   Zcls_argsr#   r#   r$   	_get_args  s    

z_subs_tree.<locals>._get_args)r7   r0   r`   r   r]   )r"   r   rn   r   currentZ
orig_chain	tree_argsr   rb   ZoclsZnew_tree_argsr#   r#   r$   ro     s&    

ro   c                 C   s>   | t krt S t| ||}t|}t|dkr4|d S t f| S )z backport of Union._subs_tree rh   r   )r   ro   r   re   r-   r   rn   r   r#   r#   r$   rp     s    rp   c                 C   s,   | j dkr| S t| ||}t| ft| S )z$ backport of GenericMeta._subs_tree N)r    ro   r   r)   r   r#   r#   r$   rq     s    
rq   c                 C   s&   | t krt S t| ||}t ft| S )z7 ad-hoc function (inspired by union) for legacy typing )r   ro   r)   r   r#   r#   r$   rr     s    rr   c                 C   sT   | d krdS t | rt| S t| r,t| S t| r<t| S t| rLt| S dS d S )NF)r7   _union_has_type_varr0   _tuple_has_type_varr.   _generic_has_type_varr/   _callable_has_type_var)r   r#   r#   r$   r_   '  s    r_   c                 C   s$   | j r | j D ]}t|r dS qdS NTF)r\   r_   r-   r   r#   r#   r$   r   6  s
    
r   c                 C   s$   | j r | j D ]}t|r dS qdS r   )r^   r_   r   r#   r#   r$   r   >  s
    
r   c                 C   s*   | j r | j D ]}t|r dS qt| jS )NT)rd   r_   Z
__result__r   r#   r#   r$   r   F  s
    
r   c                 C   s$   | j r | j D ]}t|r dS qdS r   )rZ   r_   r   r#   r#   r$   r   N  s
    
r   )N)NN)NN)NN)NN)S__doc__rK   typesrH   rI   Zmypy_extensionsr   r   rL   r   ImportErrorr   r&   r%   collections.abcr*   r:   r>   rA   rJ   r[   r	   r
   r   r   r   r   r   r   r   r   r   r   ZGenericAliasr(   r   r   r   r   r   r   r   r   r.   r/   r0   r2   r;   Z	UnionTyper<   rf   r7   r=   r   addr?   r@   rB   rR   rS   rX   rY   r]   rg   rj   r9   rx   rz   r}   r   r   r   r   r   ro   rp   rq   rr   r_   r   r   r   r   r#   r#   r#   r$   <module>   s   	",
(



 E+
D(
-


