V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
Marinej
V2EX  ›  Python

不懂就问,走火入魔了,函数对象会被 GC 吗

  •  
  •   Marinej · 2020-02-21 12:43:38 +08:00 · 3058 次点击
    这是一个创建于 1519 天前的主题,其中的信息可能已经有所发展或是发生改变。

    写装饰器的时候突然想到

    4 条回复    2020-02-22 18:59:17 +08:00
    ClericPy
        1
    ClericPy  
       2020-02-21 12:49:29 +08:00
    看情况吧, 不知道你具体怎么用的, 可以试试: 丢到 WeakSet 里, 看没有引用了以后这个 set 空了没有. 不过看 set 的时候要确保是在程序退出时候执行栈的最外层, 比如试试 atexit 或者丢到这个函数外层 class 的 __del__ 里
    PTLin
        2
    PTLin  
       2020-02-21 13:50:51 +08:00
    只要有名字绑定到一个对象上就不会被 CG
    def bar(func):
    def wrapper(*args,**kwargs):
    print(func.__name__)
    func()
    return wrapper

    @bar
    def foo():
    print('foo')
    比如这段代码,foo 被 bar 装饰之后之际上调用的是 wrapper,在 wrapper 里 func 是自由变量,上面这个代码上原始的 foo 存在 foo.__closure__[0].cell_contents 这个名字里,所以原始的 foo 还有名字绑定不会被 CG
    chenstack
        3
    chenstack  
       2020-02-21 18:19:19 +08:00
    除非在函数定义的作用域中把引用删掉了,比如
    import weakref

    def fn():
        print('I am alive')


    fn_ref = weakref.ref(fn)
    print(fn_ref())
    del fn
    print(fn_ref()) # 变成 None 了
    Marinej
        4
    Marinej  
    OP
       2020-02-22 18:59:17 +08:00
    @PTLin 嗯,自由变量还是被绑定的,谢谢解答
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5295 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 08:36 · PVG 16:36 · LAX 01:36 · JFK 04:36
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.