Python:装饰器,范围和模块导入

时间:2015-05-28 16:58:58

标签: python python-decorators

所以我试图学习使用Python(2.x)装饰器,并且在弄乱它们时,我遇到了......一个奇怪的事情。总而言之,我想我试图使用装饰器将装饰函数添加到其他地方的存储中。

我不知道这是最恐怖的做事方式,但我想了解出了什么问题。

假设我有一个模块(我作为脚本运行),如下所示:

# -*- coding: utf-8 -*-
# main.py

d = {}
b = []
def mydecorator(name):
    b.append(name)
    def decorator(fun):
        d[name] = fun
        print 'in here', d, b
        return fun
    print 'and here', d, b
    return decorator

class SomeClass:
    @mydecorator('a thing')
    def working_func(self, params):
        # do stuff
        pass

def main():
    # do stuff
    print 'out there', d, b


if __name__ == '__main__':
    main()

按预期打印:

and here {} ['a thing']
in here {'a thing': <function working_func at 0x7fd6b69e0758>} ['a thing']
out there {'a thing': <function working_func at 0x7fd6b69e0758>} ['a thing']

但是,如果我将课程移到单独的模块中

# -*- coding: utf-8 -*-
# module.py

from main import mydecorator

class AnotherClass:
    @mydecorator('boo')
    def not_workin_func(self, params):
        # do stuff
        pass

并将其导入main.py

# -*- coding: utf-8 -*-
# main.py
import module

d = {}
b = []
def mydecorator(name):
    b.append(name)
    def decorator(fun):
        d[name] = fun
        print 'in here', d, b
        return fun
    print 'and here', d, b
    return decorator

def main():
    # do stuff
    print 'out there', d, b


if __name__ == '__main__':
    main()

列表和字典中的更改不会持续:

and here {} ['boo']
in here {'boo': <function not_workin_func at 0x7fd1009917d0>} ['boo']
out there {} []

我想这与python如何处理范围/模块导入有关?

1 个答案:

答案 0 :(得分:1)

问题是循环导入,在d初始化后,字典b和列表module会被替换为空列表。

您可以通过添加一些打印语句来查看执行顺序:

module.py:

# -*- coding: utf-8 -*-
# module.py
print('  module - init')

print('  module - importing from main')
from main import mydecorator
#import main


print('  module - definiting class')
class AnotherClass:
    @mydecorator('boo')
    def not_workin_func(self, params):
        # do stuff
        pass

main.py:

# -*- coding: utf-8 -*-
# main.py

print('main - importing module')
import module

print('main - making empty d,b')
d = {}
b = []

print('main - definiting mydecorator')
def mydecorator(name):
    b.append(name)
    def decorator(fun):
        d[name] = fun
        print 'in here', d, b
        return fun
    print 'and here', d, b
    return decorator

print('main - defining main')
def main():
    # do stuff
    print 'out there', d, b

if __name__ == '__main__':
    print('main - running main')
    main()

现在,当您运行python main.py时,您可以看到以什么顺序发生的事情:

main - importing module
  module - init
  module - importing from main
main - importing module
main - making empty d,b
main - definiting mydecorator
main - defining main
  module - definiting class
and here {} ['boo']
in here {'boo': <function not_workin_func at 0x100ca4aa0>} ['boo']
main - making empty d,b
main - definiting mydecorator
main - defining main
main - running main
out there {} []

您可以看到{<1}}和d在在类定义中应用了装饰器之后被重新分配给空列表和词典

老实说,除了将装饰器和bd移出main并进入自己的模块以解决循环依赖之外,我真的无法弄清楚如何解决这个问题,但我认为如果不是严格禁止的话,大多数人都会同意尽可能避免循环进口。