简体   繁体   中英

Does Python have a similar function to std::move?

>>> cache = {}
>>> cache['1'] = 'long string'
>>> cache['2'] = 'very long string'
>>> buffer = {}
>>> buffer['1'] = cache['1']
>>> del cache['1']
>>> buffer['2'] = cache['2']
>>> del cache['2']
>>> cache
{}
>>> buffer
{'1': 'long string', '2': 'very long string'}

I have two large dictionaries(ie cache and buffer). Periodically, I need to move the content from cache to buffer and delete the copied item from cache .

Does Python offer similar function to C++11 std::move so that I don't have to make an extra copy of the item which will be removed later?

Updated based on comments from @JETM

>>> cache = {}
>>> cache['1'] = 'long string2'
>>> buffer['1'] = cache['1']
>>> id(buffer['1'])
139639957636576
>>> id(cache['1'])
139639957636576
>>> del cache['1']
>>> id(buffer['1'])
139639957636576

It looks like the value of cache['1'] is NOT copied into buffer['1'].

In this particular case, you could use dict.pop :

buffer['1'] = cache.pop('1')

It's worth noting, though, that in Python objects are more synonymous with pointers; that is, when you perform this copy, no data gets duplicated, you're just adding a reference to the object in buffer and removing a reference to it from cache . That is, only the pointer is getting copied.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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