简体   繁体   English

如果我读取一个元组而不是单个值,Python 泄漏 memory

[英]Python leaks memory if I read a tuple instead of single value

I'm querying whether a key exists in a RocksDB database using Python.我正在使用 Python 查询 RocksDB 数据库中是否存在密钥。 The API (see bottom) implies it returns a two-element tuple. API(见底部)意味着它返回一个二元素元组。 So I receive both tuple elements:所以我收到了两个元组元素:

def contains_key(database: rocksdb, key: int) -> bool:
    found, data = database.key_may_exist(key)
    return found

and I am using it like this:我正在这样使用它:

if not contains_key(database, key):

However, this causes a memory leak.但是,这会导致 memory 泄漏。

To prove this, if I change the code to:为了证明这一点,如果我将代码更改为:

def contains_key(database: rocksdb, key: int) -> bool:
    return database.key_may_exist(key)

there is no leak (but it's obviously not correct).没有泄漏(但显然不正确)。

How do I get the first version to work without a memory leak?如何让第一个版本在没有 memory 泄漏的情况下工作?

在此处输入图像描述

Your code你的代码

def contains_key(database: rocksdb, key: int) -> bool:
    found, data = database.key_may_exist(key)
    return found

does not contain a memory leak.不包含 memory 泄漏。

found and data are two names in the local scope, and both refer to values that exist in a single area of memory. founddata是本地 scope 中的两个名称,均指 memory 单个区域中存在的值。 When the function returns, found and data go out of scope.当function返回时, found scope中的data go。 What found referred to can be referred to by the caller ( x = contains_key(db, 3) ), but data is ignored.调用者可以引用found的内容( x = contains_key(db, 3) ),但忽略data Since no other reference to that object exists, Python (as a garbage-collecting language) reclaims whatever resources were devoted to data automatically.由于不存在对 object 的其他引用,因此 Python(作为垃圾收集语言)会自动回收用于data的任何资源。

For that matter, the key_may_exist method returns a tuple that you never safe a reference to.就此而言, key_may_exist方法返回一个您永远无法安全引用的元组。 It is immediately unpacked, with found and data referring to whatever that tuple referred to.它立即被解包, founddata引用了该元组所引用的任何内容。 The tuple itself is garbage-collected, but the references to its contents remain.元组本身是垃圾收集的,但对其内容的引用仍然存在。

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

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