pyjanitor-devs / pandas_flavor

The easy way to write your own flavor of Pandas
https://zsailer.github.io/software/pandas-flavor/
MIT License
301 stars 17 forks source link

EHN: Cut duplicate codes via the factory design pattern #23

Open Zeroto521 opened 2 years ago

Zeroto521 commented 2 years ago

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:

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)
ericmjl commented 1 year ago

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

asmirnov69 commented 1 year ago

@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

Zeroto521 commented 1 year ago

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.