pandas icon indicating copy to clipboard operation
pandas copied to clipboard

How to tell if Accessor is Registered

Open achapkowski opened this issue 5 years ago • 2 comments

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?

achapkowski avatar Feb 28 '20 12:02 achapkowski

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

jbrockmendel avatar Jun 28 '20 01:06 jbrockmendel

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?)

jorisvandenbossche avatar Jul 08 '20 12:07 jorisvandenbossche