1

I am learning about Decorators in python and I stumbled upon this code:

def add(x, y):
    return x+y
variable=add
print(id(add)) #returns some number 19080888
print(id(variable)) #returns the same number 19080888

print(id(add(1,2)) #returns some number 164680898
print(id(variable(1,2)) #returns different number 164680822

I can't wrap my head around it. Why is the id() of the functions the same, but that of their outputs, with the same arguments, different?

I tried looking on SO for a similar question but couldn't find one, hence had to ask it.

Karan Singh
  • 1,114
  • 1
  • 13
  • 30
  • 1
    Because you've bound the same function object to 2 different names. On the other hand your function is not required to return the same object instance between invocations, even with the same arguments. It could in case of small integers, but is not required to. Also your code has 0 decorators. Your latter calls have too few parentheses. – Ilja Everilä Jun 16 '17 at 08:17
  • `id` is really a lowlevel function, not very useful because it does what it wants... you don't have to know if 2 objects have the same id unless you're coding some very specific stuff. – Jean-François Fabre Jun 16 '17 at 08:22
  • 1
    To add to what @Jean-FrançoisFabre wrote, `id()` can be useful in some debugging scenarios and as a part of an objects `repr()`. But you usually don't want to rely on its value. – Ilja Everilä Jun 16 '17 at 08:26
  • @IljaEverilä can you explain this part "On the other hand your function is not required to return the same object instance between invocations"? – Karan Singh Jun 16 '17 at 08:30
  • @Jean-FrançoisFabre Its kind of useful for me rn as a beginner to see whats happening, because I was used to it in C – Karan Singh Jun 16 '17 at 08:31
  • You should forget such notions when coming from C. The actual value of `id()` is an implementation detail and matters very little in Python. You usually only care about the identity of an object when using the `is` operator. To explain further the return value, the function is free to create a new `int` object on each call as the result of the addition. On the other hand CPython [special cases small integers](https://stackoverflow.com/questions/306313/is-operator-behaves-unexpectedly-with-integers), but that is an implementation detail. – Ilja Everilä Jun 16 '17 at 08:43
  • Also coming from C you should read [Ned Batchelder's "Facts and myths about Python names and values"](https://nedbatchelder.com/text/names.html). – Ilja Everilä Jun 16 '17 at 08:54

0 Answers0