Search code examples
pythonpython-3.xdecoratorpython-decorators

Objects having same name refer to different id in python


In the below code snippet, two objects named div are created at lines 1 and 2.

  1. How does python differentiate between the two div objects created under the same scope?

  2. When id() is applied on both objects, two different addresses are shown for the similar named objects. Why is this so?

def div(a,b):
    return a/b


print(id(div)) # id = 199......1640 ################################ line 1


def smart_div(func):
    def inner(a,b):
        if a<b:
            a,b=b,a
        return func(a,b)
    return inner


a = int(input("Enter 1st: "))
b = int(input("Enter 2nd: "))
div = smart_div(div)
print(id(div)) # id = 199......3224 ############################# line 2
print(div(a,b)) 

In legacy languages like C, one can't create two variables with the same name under same scope. But, in python this rule does not seem to apply.


Solution

  • In languages like C you can rename a variable with different values. That is how you update a value. In C they must have the same type though because C is a statically typed language. Python on the other hand is dynamically typed which means it doesn't track types. In programs there is a table where names are associated with values and when you defined div to a new value in the same scope it just wrote over that value because the second div came later. You can no longer access the function div any longer after the new div value has been defined.