Reputation: 1175
I have a question about performance.
If I have a case when I pass a mutable object to a function and I make changes to that object, I know that in python it will change the value and all the pointers will point to the value that has been changed.
But what is the right way to write code?
Should I use the return
statement and assign all over again the pointer to the output of the function to show to the one that reads the code that it is being changed?
How hard is it hurting the performance if you preform an assignment of a pointer to the same memory it is already pointing?
Thanks!
Upvotes: 3
Views: 1609
Reputation: 1489
a) It has no significant effect on the performance.
b) If your function takes a object and changes it, this is a side-effect and you should therefore not return
that object. That would be confusing and misleading as it implies that the input is different from the output.
c) If you think you should write code that is useless just to provide information to readers of your code, use comments instead.
Upvotes: 5
Reputation: 224904
Should use the return statement and assign all over again the pointer to the output of the function to show to the one that reads the code that it is being changed?
No, that would make it more confusing. If you’re going to change an object in place, you should make it obvious, and part of making it obvious is not returning the same object. Take existing Python APIs as inspiration:
>>> import random
>>> a = [1, 2, 3]
>>> random.shuffle(a)
random.shuffle
didn’t return anything, so the only thing it could have done was shuffle the list in place.
Performance is irrelevant here.
Upvotes: 10