When accessing a variable or a member of an object, python performs a dictionary lookup (in locals()
, globals()
, class.__dict__
... you name it)
So with this:
id = user.status.id
first you're shadowing id
(which gets IDs of objects) but you're doing 3 dictionary lookups (user
, status
and id
)
Aliasing user.status
to status
makes the code slightly faster (very slightly with only 2 dict lookups)
This technique is used in an answer of the famous question How do you remove duplicates from a list whilst preserving order?
def f7(seq):
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]
seen_add
is an alias for seen.add
. Saves one lookup.
In your case, it also makes it easier to read ( because the same pattern isn't repeated several times (and also more "object oriented" since you're defining a context more clearly).
And that's true in all languages (even if compiled languages are able to recognize repeated accesses and alias them in the binary, something python can't do)