小编ato*_*ter的帖子

Pythonic复制可迭代对象的方法

对于我正在研究的小项目,我需要循环查看列表.对于这个循环的每个元素,我必须通过相同的列表开始另一个循环,前一个元素作为新循环的第一个元素.例如,我希望能够生成这样的东西:

1, 2, 3, 4, 1, 2, 3, 4, 1, ...
2, 3, 4, 1, 2, 3, 4, 1, 2, ...
3, 4, 1, 2, 3, 4, 1, 2, 3, ...
4, 1, 2, 3, 4, 1, 2, 3, 4, ...
1, 2, 3, 4, 1, 2, 3, 4, 1, ...
...
Run Code Online (Sandbox Code Playgroud)

我认为在每个.next()之后复制一个itertools.cycle会保留当前状态,这样我就可以用"外部"循环中的元素开始新的循环.甚至"将循环指针"重置为较旧的位置.我尝试了以下方法:

>>> import itertools, copy
>>> a = itertools.cycle([1, 2, 3, 4])
>>> b = copy.copy(a)
Run Code Online (Sandbox Code Playgroud)

但得到了这个错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module> …
Run Code Online (Sandbox Code Playgroud)

python copy cycle python-itertools

5
推荐指数
1
解决办法
4897
查看次数

在运行时获取 python 装饰器参数

有没有什么方法可以在运行时获取装饰器函数的参数?我正在从事的项目非常庞大,重写受影响的代码将需要付出巨大的努力。我需要一个动态解决方案来列出分配给函数列表的所有“类别”。为此,我想避免超级黑客解决方案,例如通过我的所有模块进行重新调整。这可以通过检查调用堆栈中的帧来完成吗?

在我们的环境中,函数是对象方法,并且我们也使用链式装饰器。为了便于理解,我将这段代码放在一起。

如果这是不可能的,我可以为项目的某些部分组合另一个装饰器,尽管这会增加更多的复杂性。但欢迎任何解决我的问题的建议。

def check(*args):
    # do something project relevant, so just return True
    return True

def decorate(*categories):
    def wrap(f):
        def wrap_check_categories(*args, **kwargs):
            if check(*categories):
                return f(*args, **kwargs)
            else:
                raise Exception
        return wrap_check_categories
    return wrap

def get_categories(f):
    '''Returns decorator parameters'''
    # ... do some magic here
    raise NotImplementedError

@decorate('foo', 'bar')
def fancy_func(*args, **kwargs):
    return args, kwargs

def main():
    ## should output ['foo', 'bar']
    print get_categories(fancy_func)

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

python introspection python-2.7 python-decorators

5
推荐指数
1
解决办法
2059
查看次数