update:2017-9-1
每到deadline開發(fā)都十分有動力钢属,XD鬓长。
分布式模塊celery
Django后端
- 遇到一個和循環(huán)引用相關的問題磷箕,類似下面的情況:
class B(object):
def __init__(self, arg):
self.arg = arg
class A(object):
def __init__(self):
self.b = B(self)
a = A()
不確定python的回收機制會不會處理這樣的情況,谷歌一番后找到了一個解決的方法哑子。
首先在overflow上看到這么一個回答
"Worry" is misplaced, but if your program turns out to be slow,consume more
memory than expected, or have strange inexplicable pauses,the cause is
indeed likely to be in those garbage reference loops -- they need to be
garbage collected by a different procedure than "normal" (acyclic) reference
graphs, and that collection is occasional and may be slow if you have a lot
of objects tied up in such loops
大概的意思是對循環(huán)引用的回收不太靠譜?肌割?卧蜓?
然后看到了一個解決循環(huán)引用的方法,就是weakref這個包把敞。
使用起來很方便弥奸,import 這個包,然后在需要的位置加上weakref.ref
函數(shù)就好了奋早。
比如對上面函數(shù)的修改
class B(object):
def __init__(self, arg):
self.arg = weakref.ref(arg)
class A(object):
def __init__(self):
self.b = B(self)
a = A()
兩次運行打印A的對象就會發(fā)現(xiàn)不同盛霎。
第一次
without weakref
第二次
with weakref
最后,使用加了weakref的對象使用屬性的時候耽装,比如要用A的a屬性愤炸,要寫A().a的形式。