pandas-dev / pandas

Flexible and powerful data analysis / manipulation library for Python, providing labeled data structures similar to R data.frame objects, statistical functions, and much more
https://pandas.pydata.org
BSD 3-Clause "New" or "Revised" License
43.71k stars 17.93k forks source link

How to tell if Accessor is Registered #32330

Open achapkowski opened 4 years ago

achapkowski commented 4 years ago

I have a simple question:

How do you know if your accessor namespace has already been registered with the extension framework?

Let's say I do:

import pandas as pd
import coolaccessor # registers dataframe accessor/namespace

Now later on in the code, a person does:

def cool_function(a,b):
   import coolaccessor
   return pd.cool.shibby(a,b)

It will try to re-register the accessor. This produces a warning during testing if that case occurs. So how can I check that if on re-import the registration doesn't need to occur again?

jbrockmendel commented 4 years ago

cc @jorisvandenbossche is there a recommended way to do this?

jorisvandenbossche commented 4 years ago

I don't think there is anything accessor-registry-specific. The registering code basically does

    def decorator(accessor):
        if hasattr(cls, name):
            warnings.warn(
                f"registration of accessor {repr(accessor)} under name "
                f"{repr(name)} for type {repr(cls)} is overriding a preexisting "
                f"attribute with the same name.",
                UserWarning,
                stacklevel=2,
            )
        setattr(cls, name, CachedAccessor(name, accessor))
        cls._accessors.add(name)
        return accessor

So the actual check it does for this warning is hasattr(cls, name).

(I find it a bit surprising that python imports the library twice. Or is it because the other import is in a function?)