简体   繁体   English

Python中的MemoryViews和垃圾收集

[英]MemoryViews and Garbage Collection in Python

Basically: 基本上:

If I declare a bytearray somewhere: 如果我在某处声明一个bytearray:

arr = bytearray(somestr)

Then create a memoryview of it: 然后创建它的内存视图:

view = memoryview(arr)

Can I be sure that for as long as I have a reference to the view object somewhere, that the bytearray will remain? 我可以确定只要我在某个地方引用了视图对象,那么bytearray将会保留吗?

ie: 即:

def foo():
    arr = bytearray("hello world")
    return memoryview(arr)

view = foo()

Will garbage collection ever remove the original bytearray? 垃圾收集是否会删除原始的bytearray? Or does this count as a reference? 或者这算作参考?

It counts as a reference. 它算作参考。 However you can call release() on the view to remove that reference: 但是,您可以在视图上调用release()以删除该引用:

>>> class A(bytes):
...     def __del__(self):print('called')
... 
>>> a =A()
>>> m = memoryview(a)
>>> del a
>>> m
<memory at 0x7fddcb00a288>
>>> len(m)
0
>>> m.release()
called

Note that you can access the underlying object from the view using the obj attribute . 请注意,您可以使用obj属性从视图中访问基础对象。

In generaly, anything that is not described explicitly as a weak reference holds an actual reference. 一般来说,任何未明确描述为弱引用的东西都有实际的参考。 In memory-managed languages that's the default. 在内存管理语言中,这是默认语言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM