Skip to content

Instantly share code, notes, and snippets.

@EdwinChan
Created November 24, 2022 05:13
Show Gist options
  • Select an option

  • Save EdwinChan/26745e4c45390491daaaec7ab095ab11 to your computer and use it in GitHub Desktop.

Select an option

Save EdwinChan/26745e4c45390491daaaec7ab095ab11 to your computer and use it in GitHub Desktop.
Transferring ownership of function argument to function in Python (aka move semantics)
import psutil
def rss(label):
print(label, psutil.Process().memory_info().rss)
class Wrapper:
def __init__(self, value):
self.value = value
def __call__(self):
value = self.value
del self.value
return value
def copy():
def copy_func(x):
rss('entered function')
del x
rss('done with object')
rss('[copy test]')
x = [None] * 10**8
rss('initialized object')
copy_func(x)
rss('exited function')
def move():
def move_func(x):
rss('entered function')
x = x()
rss('unwrapped object')
del x
rss('done with object')
rss('[move test]')
x = [None] * 10**8
x = Wrapper(x)
rss('initialized object')
move_func(x)
rss('exited function')
if __name__ == '__main__':
copy()
print()
move()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment