From fc76ec88ef02cfd363a5bce2c8d85bfc2ec67373 Mon Sep 17 00:00:00 2001 From: Tom Augspurger Date: Sun, 20 Jan 2019 19:40:58 -0600 Subject: [PATCH] DOC: Document AttributeError for accessor Closes https://github.com/pandas-dev/pandas/issues/20579 --- doc/source/extending.rst | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/doc/source/extending.rst b/doc/source/extending.rst index 3cb7e1ae019e1..e6928d9efde06 100644 --- a/doc/source/extending.rst +++ b/doc/source/extending.rst @@ -28,8 +28,14 @@ decorate a class, providing the name of attribute to add. The class's @pd.api.extensions.register_dataframe_accessor("geo") class GeoAccessor(object): def __init__(self, pandas_obj): + self._validate(pandas_obj) self._obj = pandas_obj + @staticmethod + def _validate(obj): + if 'lat' not in obj.columns or 'lon' not in obj.columns: + raise AttributeError("Must have 'lat' and 'lon'.") + @property def center(self): # return the geographic center point of this DataFrame @@ -54,6 +60,13 @@ This can be a convenient way to extend pandas objects without subclassing them. If you write a custom accessor, make a pull request adding it to our :ref:`ecosystem` page. +We highly recommend validating the data in your accessor's `__init__`. +In our ``GeoAccessor``, we validate that the data contains the expected columns, +raising an ``AttributeError`` when the validation fails. +For a ``Series`` accessor, you should validate the ``dtype`` if the accessor +applies only to certain dtypes. + + .. _extending.extension-types: Extension Types