Created
November 24, 2022 05:13
-
-
Save EdwinChan/26745e4c45390491daaaec7ab095ab11 to your computer and use it in GitHub Desktop.
Transferring ownership of function argument to function in Python (aka move semantics)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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