I don't know what it is, but I'm curious about this. To add additional variables to an already defined function.

Asked 2 years ago, Updated 2 years ago, 334 views

from shapely.geometry import Point

def somefunc(lst):
    return [Point(x) for x in lst]

if __name__ == "__main__":
    xy = [(x, x) for x in range(1, 10)]
    print(somefunc(xy))
 There is a need to add a count variable to somefunc in this state,
def somefunc(lst, count=False):
    zz = [Point(x) for x in lst]
    if count:
        return [(id,x) for x in enumerate(zz)]
    return zz
I changed it like this.

Is there a way to support the count without touching some func?

Thank you.

python decorator

2022-10-31 13:40

1 Answers

Please refer to the following.

import functools
def insert_count(count):
    def decorator(func):
        @functools.wraps(func)
        def _wrap(*args, **kwargs):
            zz = func(*args, **kwargs)
            if count:
                return [(id,x) for x in enumerate(zz)]
            return zz
        return _wrap
    return decorator

from shapely.geometry import Point

@insert_count(True)
def somefunc(lst):
    return [Point(x) for x in lst]

result = somefunc(zip(range(1, 11), range(1, 11)))


2022-10-31 13:40

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.