pandas_flavor
pandas_flavor copied to clipboard
EHN: Cut duplicate codes via the factory design pattern
I saw there have a lot of duplicate codes. And they both have the same structure. Maybe we could extract the same codes via the factory design pattern?
Duplicate codes:
- https://github.com/Zsailer/pandas_flavor/blob/f9308140d559ef1cb80587dedf6a7e32ca1f0b67/pandas_flavor/register.py#L19-L26
- https://github.com/Zsailer/pandas_flavor/blob/f9308140d559ef1cb80587dedf6a7e32ca1f0b67/pandas_flavor/register.py#L38-L47
- https://github.com/Zsailer/pandas_flavor/blob/f9308140d559ef1cb80587dedf6a7e32ca1f0b67/pandas_flavor/xarray.py#L13-L21
The prototype of this idea.
It could work for pandas-like object, such as pandas.DataFrame
, pandas.Series
, pandas.Index
, geopandas.GeoDataFrame
, and geopandas.GeoSeries
.
def register_method_factory(register_accessor):
@wraps(register_accessor)
def decorator(method):
def method_accessor(pd_obj):
@wraps(method)
def wrapper(*args, **kwargs):
return method(pd_obj, *args, **kwargs)
return wrapper
# Register method as pandas object inner method.
register_accessor(method.__name__)(method_accessor)
# Must return method itself, otherwise would get None.
return method
return decorator
# or register_dataframe_method = register_method_factory(register_dataframe_accessor)
@register_method_factory
def register_dataframe_method(method):
"""Docstring"""
return register_dataframe_accessor(method)
@register_method_factory
def register_dataarray_method(method):
"""Docstring"""
return register_dataarray_accessor(method)
@Zeroto521 this feels like a great way to enable arbitrary dataframe extensions, perhaps even to other up-and-coming dataframe libraries. How would you like to move forward here?
@ericmjl @Zeroto521 also, note that this is exactly the place where pyjviz dev require to insert some additional logic (wip on pyjviz-callbacks branch) -> https://github.com/pyjanitor-devs/pandas_flavor/blob/69d45e1defdf6e2fd86b756e238517b4609ac929/pandas_flavor/register.py#L38
This feature already finished in https://github.com/Zeroto521/my-data-toolkit/blob/main/dtoolkit/accessor/register.py And an example of geopandas, use this wrapper to decorate geopandas.GeoDataFrame (https://github.com/Zeroto521/my-data-toolkit/blob/main/dtoolkit/geoaccessor/register.py)
PS: I need to focus on my work recently so that any open-source activities will get late.