U
    MZf&                     @  s   d Z ddlmZ ddlmZmZ ddlZddlmZ ddl	m
Z
 G dd dZG d	d
 d
Zddd dfddddddddZG dd dZeddddd Zeedddd Zeed dd!d" Zeed#dd$d% ZdS )&z

accessor.py contains base classes for implementing accessor properties
that can be mixed into or pinned onto other pandas classes.

    )annotations)CallablefinalN)doc)find_stack_levelc                      s`   e Zd ZU e Zded< e Zded< eddddZ	dddd	Z
d
d fddZ  ZS )DirNamesMixinzset[str]
_accessorszfrozenset[str]_hidden_attrs)returnc                 C  s   | j | jB S )z:
        Delete unwanted __dir__ for this object.
        )r   r	   self r   8/tmp/pip-unpacked-wheel-nbcvw55c/pandas/core/accessor.py_dir_deletions   s    zDirNamesMixin._dir_deletionsc                   s    fdd j D S )z9
        Add additional __dir__ for this object.
        c                   s   h | ]}t  |r|qS r   )hasattr).0accessorr   r   r   	<setcomp>"   s     
 z/DirNamesMixin._dir_additions.<locals>.<setcomp>)r   r   r   r   r   _dir_additions   s    zDirNamesMixin._dir_additions	list[str]c                   s*   t t  }||   |  B }t|S )z
        Provide method name lookup and completion.

        Notes
        -----
        Only provide 'public' methods.
        )setsuper__dir__r   r   sorted)r   rv	__class__r   r   r   $   s    zDirNamesMixin.__dir__)__name__
__module____qualname__r   r   __annotations__	frozensetr	   r   r   r   r   __classcell__r   r   r   r   r      s   
r   c                	   @  sP   e Zd ZdZdd Zdd Zdd Zedd	d
 dfdddddddddZdS )PandasDelegatez@
    Abstract base class for delegating methods/properties.
    c                 O  s   t d| d S )NzYou cannot access the property 	TypeErrorr   nameargskwargsr   r   r   _delegate_property_get6   s    z%PandasDelegate._delegate_property_getc                 O  s   t d| dd S )NzThe property z cannot be setr$   )r   r'   valuer(   r)   r   r   r   _delegate_property_set9   s    z%PandasDelegate._delegate_property_setc                 O  s   t d| d S )NzYou cannot call method r$   r&   r   r   r   _delegate_method<   s    zPandasDelegate._delegate_methodFc                 C  s   | S Nr   xr   r   r   <lambda>F       zPandasDelegate.<lambda>Tr   strboolCallable[[str], str]None)	accessorstyp	overwriteaccessor_mappingraise_on_missingr
   c                   sx    fdd} fdd}|D ]R}	|s>t  |	ddkr>q |dkrP||	}
n||	}
|sft| |	s t| |	|
 q dS )a  
        Add accessors to cls from the delegate class.

        Parameters
        ----------
        cls
            Class to add the methods/properties to.
        delegate
            Class to get methods/properties and doc-strings.
        accessors : list of str
            List of accessors to add.
        typ : {'property', 'method'}
        overwrite : bool, default False
            Overwrite the method/property in the target class if it exists.
        accessor_mapping: Callable, default lambda x: x
            Callable to map the delegate's function to the cls' function.
        raise_on_missing: bool, default True
            Raise if an accessor does not exist on delegate.
            False skips the missing accessor.
        c                   s>    fdd} fdd} |_  |_ t||t jdS )Nc                   s
   |   S r.   )r*   r   r'   r   r   _getter_   s    z[PandasDelegate._add_delegate_accessors.<locals>._create_delegator_property.<locals>._getterc                   s   |   |S r.   )r,   )r   Z
new_valuesr<   r   r   _setterb   s    z[PandasDelegate._add_delegate_accessors.<locals>._create_delegator_property.<locals>._setter)fgetfsetr   )r   propertygetattr__doc__)r'   r=   r>   r:   delegater<   r   _create_delegator_property^   s    zJPandasDelegate._add_delegate_accessors.<locals>._create_delegator_propertyc                   s(    fdd} |_ t j|_|S )Nc                   s   | j  f||S r.   )r-   )r   r(   r)   r<   r   r   fo   s    zSPandasDelegate._add_delegate_accessors.<locals>._create_delegator_method.<locals>.f)r   rB   rC   )r'   rG   rD   r<   r   _create_delegator_methodn   s    zHPandasDelegate._add_delegate_accessors.<locals>._create_delegator_methodNrA   )rB   r   setattr)clsrE   r7   r8   r9   r:   r;   rF   rH   r'   rG   r   rD   r   _add_delegate_accessors?   s    	
z&PandasDelegate._add_delegate_accessorsN)	r   r   r   rC   r*   r,   r-   classmethodrK   r   r   r   r   r#   1   s   r#   Fc                 C  s   | S r.   r   r/   r   r   r   r1      r2   r1   Tr   r3   r4   r5   )r7   r8   r9   r:   r;   c                   s    fdd}|S )a  
    Add delegated names to a class using a class decorator.  This provides
    an alternative usage to directly calling `_add_delegate_accessors`
    below a class definition.

    Parameters
    ----------
    delegate : object
        The class to get methods/properties & doc-strings.
    accessors : Sequence[str]
        List of accessor to add.
    typ : {'property', 'method'}
    overwrite : bool, default False
       Overwrite the method/property in the target class if it exists.
    accessor_mapping: Callable, default lambda x: x
        Callable to map the delegate's function to the cls' function.
    raise_on_missing: bool, default True
        Raise if an accessor does not exist on delegate.
        False skips the missing accessor.

    Returns
    -------
    callable
        A class decorator.

    Examples
    --------
    @delegate_names(Categorical, ["categories", "ordered"], "property")
    class CategoricalAccessor(PandasDelegate):
        [...]
    c                   s   | j  d | S )N)r9   r:   r;   )rK   )rJ   r:   r7   rE   r9   r;   r8   r   r   add_delegate_accessors   s    z.delegate_names.<locals>.add_delegate_accessorsr   )rE   r7   r8   r9   r:   r;   rN   r   rM   r   delegate_names   s    (rO   c                   @  s(   e Zd ZdZdddddZdd Zd	S )
CachedAccessora  
    Custom property-like object.

    A descriptor for caching accessors.

    Parameters
    ----------
    name : str
        Namespace that will be accessed under, e.g. ``df.foo``.
    accessor : cls
        Class with the extension methods.

    Notes
    -----
    For accessor, The class's __init__ method assumes that one of
    ``Series``, ``DataFrame`` or ``Index`` as the
    single argument ``data``.
    r3   r6   )r'   r
   c                 C  s   || _ || _d S r.   )_name	_accessor)r   r'   r   r   r   r   __init__   s    zCachedAccessor.__init__c                 C  s,   |d kr| j S |  |}t|| j| |S r.   )rR   object__setattr__rQ   )r   objrJ   Zaccessor_objr   r   r   __get__   s
    
zCachedAccessor.__get__N)r   r   r   rC   rS   rW   r   r   r   r   rP      s   rP    )klassZothersc                   s    fdd}|S )aG  
    Register a custom accessor on {klass} objects.

    Parameters
    ----------
    name : str
        Name under which the accessor should be registered. A warning is issued
        if this name conflicts with a preexisting attribute.

    Returns
    -------
    callable
        A class decorator.

    See Also
    --------
    register_dataframe_accessor : Register a custom accessor on DataFrame objects.
    register_series_accessor : Register a custom accessor on Series objects.
    register_index_accessor : Register a custom accessor on Index objects.

    Notes
    -----
    When accessed, your accessor will be initialized with the pandas object
    the user is interacting with. So the signature must be

    .. code-block:: python

        def __init__(self, pandas_object):  # noqa: E999
            ...

    For consistency with pandas methods, you should raise an ``AttributeError``
    if the data passed to your accessor has an incorrect dtype.

    >>> pd.Series(['a', 'b']).dt
    Traceback (most recent call last):
    ...
    AttributeError: Can only use .dt accessor with datetimelike values

    Examples
    --------
    In your library code::

        import pandas as pd

        @pd.api.extensions.register_dataframe_accessor("geo")
        class GeoAccessor:
            def __init__(self, pandas_obj):
                self._obj = pandas_obj

            @property
            def center(self):
                # return the geographic center point of this DataFrame
                lat = self._obj.latitude
                lon = self._obj.longitude
                return (float(lon.mean()), float(lat.mean()))

            def plot(self):
                # plot this array's data on a map, e.g., using Cartopy
                pass

    Back in an interactive IPython session:

        .. code-block:: ipython

            In [1]: ds = pd.DataFrame({{"longitude": np.linspace(0, 10),
               ...:                    "latitude": np.linspace(0, 20)}})
            In [2]: ds.geo.center
            Out[2]: (5.0, 10.0)
            In [3]: ds.geo.plot()  # plots data on a map
    c                   s^   t  r<tjdt|  dt dt  dtt d t t|   j	 | S )Nzregistration of accessor z under name z
 for type z: is overriding a preexisting attribute with the same name.)
stacklevel)
r   warningswarnreprUserWarningr   rI   rP   r   add)r   rJ   r'   r   r   	decorator2  s    
"z%_register_accessor.<locals>.decoratorr   )r'   rJ   ra   r   r`   r   _register_accessor   s    Irb   	DataFrame)rY   c                 C  s   ddl m} t| |S )Nr   )rc   )pandasrc   rb   )r'   rc   r   r   r   register_dataframe_accessorB  s    re   Seriesc                 C  s   ddl m} t| |S )Nr   )rf   )rd   rf   rb   )r'   rf   r   r   r   register_series_accessorI  s    rg   Indexc                 C  s   ddl m} t| |S )Nr   )rh   )rd   rh   rb   )r'   rh   r   r   r   register_index_accessorP  s    ri   )rC   
__future__r   typingr   r   r[   Zpandas.util._decoratorsr   Zpandas.util._exceptionsr   r   r#   rO   rP   rb   re   rg   ri   r   r   r   r   <module>   s(   [<%

X




