2

I have an sqlalchemy query that returns a tuple. I pass this tuple to a function, and since it's an immutable type, a new instance of the tuple is created in the called function.

How does python deal with this in terms of memory management? Is a complete copy of the tuple created, or is it using some clever 'copy on write/zero copy' like functionality?

The problem for me is that these original tuples can consume large amounts of memory, and just by calling a function to do some processing on them, Python will effectively double the memory consumption.

With the exception of writing the code inline, how can I avoid such inefficiency?

2 Answers 2

2

When you call a function, just a reference to the tuple gets passed, not a copy. The fact that it's immutable doesn't mean that it will be copied on a function call, just that you can't modify it.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok, according to: [link] testingreflections.com/node/view/5126 "Some objects, like strings, tuples, and numbers, are immutable. Altering them inside a function/method will create a new instance and the original instance outside the function/method is not changed." Does this mean a new instance is created only when an attempt to modify the passed tuple/string is made?
Yup, you pass the reference by value (small), but the object it's referencing (large) isn't being copied.
0

Python passes references to objects by value. So you dont need to worry about it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.