1

I have 2 classes as so:

class Status:
    id = 1
    text = "blah"

class User:
    status = StatusObject

In my program, I need to get the Status' ID and text.

Which of these two solutions is the more efficient/more accepted?

Solution 1:

status = User.status
id = status.id
text = status.text

Solution 2:

id = user.status.id
text = user.status.text

thanks!

wtreston
  • 1,051
  • 12
  • 28
  • Also i know the title is terrible I just didnt know how to phrase it – wtreston Jul 26 '19 at 13:59
  • Possible duplicate of: [Should I store a calculation in a variable if it will be used a lot?](https://stackoverflow.com/questions/55542474/should-i-store-a-calculation-in-a-variable-if-it-will-be-used-a-lot) – t3m2 Jul 26 '19 at 17:14

1 Answers1

2

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)

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • So with ```id = user.status.id``` python is first looking in users dictionary for the status attribute, and then a second search in status' dictionary of attributes for id. Therefore aliasing ```user.status``` to status reduces the number of lookups making it a very small amount faster. Have I understood that correctly? – wtreston Jul 26 '19 at 14:17
  • yes. Each token means a lookup. – Jean-François Fabre Jul 26 '19 at 14:18
  • Thank you very much for your help! – wtreston Jul 26 '19 at 14:19