Reputation: 3344
Suppose there is an Object with id
among other attributes.
Suppose there is a generic function that would only need object.id
for process (ex: retrieving object value from database from id)
Does it cost more in Python 3 (memory-wise or performance) to do:
def my_function(self, id):
do_stuff_with(id)
my_function(my_object.id)
or
def my_function(self, obj):
do_struff_with(obj.id)
my_function(my_object)
I imagine that answer depends on languages implementations, so I was wondering if there is an additional cost with object as argument in Python 3, since I feel it's more flexible (imagine that in the next implementation of this function you also need object.name, then you don't have to modify the signature)
Upvotes: 6
Views: 2936
Reputation: 160357
In both cases, an object reference is passed to the function, I don't know how other implementations do this but, think C
pointers to Python Objects for CPython
(so same memory to make that call).
Also, the dot look-up in this case doesn't make a difference, you either perform a look-up for the id
during the function call or you do it inside the body (and, really, attribute look-ups shouldn't be a concern).
In the end, it boils down to what makes more sense, passing the object and letting the function do what it wants with it is better conceptually. It's also is more flexible, as you stated, so pass the class instance.
Upvotes: 6