在装饰器中实现的Python静态变量不会重置

时间:2018-07-19 17:40:39

标签: python python-decorators static-variables

我这里有实现静态变量装饰器的代码。但是,我发现如果我多次运行此函数,则每次调用该函数时,静态变量都不会重新初始化。

def static_vars(**kwargs):
    def decorate(func):
        for k in kwargs:
            setattr(func, k, kwargs[k])
        return func
    return decorate


@static_vars(count=0)
def rolling_serial(val):
    '''
    For a vector V = [v_1, ..., V_N] returns a serial
    index.

    so for V = [1, 1, 1, 3, 1, 1, 1]
    a resulting vector will be generated
    V_hat = [1, 2, 3, 4, 5, 6, 7]
    '''
    temp = rolling_serial.count
    rolling_serial.count += 1

    return temp

# invoke it like this
from useful import (rolling_serial)

df = <...some dataframe with a column called ts>

self.df['ts_index'] = self.df.ts.apply(rolling_serial)
# Example output a new column, sa: [1, 2, 3, ..., N]

# My issue arises if I run it again
df = <...some dataframe with a column called ts>
self.df['ts_index'] = self.df.ts.apply(rolling_serial)
# output: [N+1, N+2, ...] instead of restarting at 0

如果重新启动jupyter内核,则静态变量将清除。但是我宁愿不必重新启动内核。谁能帮我吗?

2 个答案:

答案 0 :(得分:1)

您的装饰器仅被调用一次,而不是对函数的每次调用。确实是在定义时调用的:

def static_vars(**kwargs):
    def decorate(func):
        for k in kwargs:
            print(kwargs)
            setattr(func, k, kwargs[k])
        return func
    return decorate


@static_vars(count=0)
def rolling_serial(val):
    '''
    For a vector V = [v_1, ..., V_N] returns a serial
    index.

    so for V = [1, 1, 1, 3, 1, 1, 1]
    a resulting vector will be generated
    V_hat = [1, 2, 3, 4, 5, 6, 7]
    '''
    temp = rolling_serial.count
    rolling_serial.count += 1
    return temp

print('---- BEGIN ----')
print(rolling_serial(10))
print(rolling_serial(20))
print(rolling_serial(30))

打印:

{'count': 0}
---- BEGIN ----
0
1
2

您在kwargs中作为参数的static_vars()将变为闭包,并且每次调用rolling_serial()时都会递增。

一种解决方案是通过globals()传递变量:

# This function creates decorator:
def static_vars(**global_kwargs):
    # This is decorator:
    def decorate(func):
        # This function is called every time:
        def _f(*args, **kwargs):
            for k in global_kwargs:
                globals()[func.__name__+'_'+k] = global_kwargs[k]
            return func(*args, **kwargs)
        return _f
    return decorate

@static_vars(count=0, temp=40)
def rolling_serial():
    global rolling_serial_count, rolling_serial_temp

    temp1, temp2 = rolling_serial_count, rolling_serial_temp
    rolling_serial_count += 1
    rolling_serial_temp += 1
    return temp1, temp2

print(rolling_serial()) # prints (0, 40)
print(rolling_serial()) # prints (0, 40)
print(rolling_serial()) # prints (0, 40)

答案 1 :(得分:1)

@装饰器正在发展,因为它打算在函数定义时装饰一次。

因此,将其裁剪并简化为传入函数上的setattr关键字args。这是您必须手动执行的操作,减去了@语法的缩写。

def static_vars(func, **kwargs):
    for k in kwargs:
        setattr(func, k, kwargs[k])
    return func


def rolling_serial(val):
    temp = rolling_serial.count
    rolling_serial.count += 1
    return temp    

static_vars(rolling_serial, count=0)
print (rolling_serial(3))
print (rolling_serial(3))

#reset it
static_vars(rolling_serial, count=0)
print (rolling_serial(3))

输出:

0
1
0

另外,FWIW,您不要使用val并且数据框不是紧密相关的,最好单独发布rolling_serial的某些预期结果。