U
    f/e                     @  s   d dl mZ d dlmZ d dlZd dlmZ d dlZd dlm	Z	 d dl
Z
d dlZd dlmZmZ d dlZd dlmZ edd	 Zed
dddZeddddddZedd Zedd Zedd ZedddZG dd dZdS )     )annotations)contextmanagerN)Path)rmtree)IOAny)
get_handlec              	   c  s(   t | d|dd}|jV  W 5 Q R X dS )a  
    Open a compressed file and return a file object.

    Parameters
    ----------
    path : str
        The path where the file is read from.

    compression : {'gzip', 'bz2', 'zip', 'xz', None}
        Name of the decompression to use

    Returns
    -------
    file object
    rbF)compressionZis_textN)r   handle)pathr
   r    r   </tmp/pip-unpacked-wheel-tiezk1ph/pandas/_testing/contexts.pydecompress_file   s    r   strtzc                 #  sL   ddl  ddl fdd} jd}||  z
dV  W 5 || X dS )a  
    Context manager for temporarily setting a timezone.

    Parameters
    ----------
    tz : str
        A string representing a valid timezone.

    Examples
    --------
    >>> from datetime import datetime
    >>> from dateutil.tz import tzlocal
    >>> tzlocal().tzname(datetime.now())
    'IST'

    >>> with set_timezone('US/Eastern'):
    ...     tzlocal().tzname(datetime.now())
    ...
    'EDT'
    r   Nc                   sB   | d kr,z j d= W q> tk
r(   Y q>X n|  j d<   d S )NTZ)environKeyErrortzsetr   ostimer   r   setTZB   s    
zset_timezone.<locals>.setTZr   )r   r   r   get)r   r   Zorig_tzr   r   r   set_timezone)   s    

r   Fboolr   )return_filelikekwargsc              	   k  s   t t }| dkrd} dtjtjtj dd|  } ||  }|	  t
|}|rl|dd t|f|}z
|V  W 5 t|t
s|  | r|  X dS )az  
    Gets a temporary path and agrees to remove on close.

    This implementation does not use tempfile.mkstemp to avoid having a file handle.
    If the code using the returned path wants to delete the file itself, windows
    requires that no program has a file handle to it.

    Parameters
    ----------
    filename : str (optional)
        suffix of the created file.
    return_filelike : bool (default False)
        if True, returns a file-like which is *always* cleaned. Necessary for
        savefig and other functions which want to append extensions.
    **kwargs
        Additional keywords are passed to open().

    N    )kmodezw+b)r   tempfile
gettempdirjoinrandomchoicesstringascii_lettersdigitstouchr   
setdefaultopen
isinstancecloseis_fileunlink)filenamer   r   folderr   Zhandle_or_strr   r   r   ensure_cleanT   s"    

r5   c                  c  s@   t jdd} z
| V  W 5 zt|  W n tk
r8   Y nX X dS )z{
    Get a temporary directory path and agrees to remove on close.

    Yields
    ------
    Temporary directory path
    r    )suffixN)r$   mkdtempr   OSError)Zdirectory_namer   r   r   ensure_clean_dir   s    	
r9   c               	   c  s2   t tj} z
dV  W 5 tj  tj|  X dS )z
    Get a context manager to safely set environment variables

    All changes will be undone on close, hence environment variables set
    within this contextmanager will neither persist nor change global state.
    N)dictr   r   clearupdate)Zsaved_environr   r   r   !ensure_safe_environment_variables   s
    


r=   c                 k  sD   ddl }dddh}| |kr"td|j| f| dV  ||  dS )au  
    Context manager to temporarily register a CSV dialect for parsing CSV.

    Parameters
    ----------
    name : str
        The name of the dialect.
    kwargs : mapping
        The parameters for the dialect.

    Raises
    ------
    ValueError : the name of the dialect conflicts with a builtin one.

    See Also
    --------
    csv : Python's CSV library.
    r   Nexcelz	excel-tabunixz Cannot override builtin dialect.)csv
ValueErrorregister_dialectunregister_dialect)namer   r@   Z_BUILTIN_DIALECTSr   r   r   with_csv_dialect   s    
rE   c                 c  sP   ddl m} |d kr|j}|j}|j}||  ||_d V  ||_|| d S )Nr   )expressions)Zpandas.core.computationrF   Z_MIN_ELEMENTSZUSE_NUMEXPRZset_use_numexpr)ZuseZmin_elementsexprZolduseZoldminr   r   r   use_numexpr   s    
rH   c                   @  s(   e Zd ZdZdd Zdd Zdd ZdS )	
RNGContexta,  
    Context manager to set the numpy random number generator speed. Returns
    to the original value upon exiting the context manager.

    Parameters
    ----------
    seed : int
        Seed for numpy.random.seed

    Examples
    --------
    with RNGContext(42):
        np.random.randn()
    c                 C  s
   || _ d S N)seed)selfrK   r   r   r   __init__   s    zRNGContext.__init__c                 C  s   t j | _t j| j d S rJ   )npr'   Z	get_statestart_staterK   )rL   r   r   r   	__enter__   s    zRNGContext.__enter__c                 C  s   t j| j d S rJ   )rN   r'   Z	set_staterO   )rL   exc_type	exc_value	tracebackr   r   r   __exit__   s    zRNGContext.__exit__N)__name__
__module____qualname____doc__rM   rP   rT   r   r   r   r   rI      s   rI   )NF)N)
__future__r   
contextlibr   r   pathlibr   r'   shutilr   r)   r$   typingr   r   ZnumpyrN   Zpandas.io.commonr   r   r   r5   r9   r=   rE   rH   rI   r   r   r   r   <module>   s2   
*,


