2

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.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
give_it_a_bit
  • 189
  • 2
  • 14
  • 2
    `div = smart_div(div)` overwrites the `div` object. you're getting a different id value because it's no longer defined by `def div`. if you `print(div)` you can see that this object now refers to the function smart_div. – David Zemens Aug 12 '19 at 16:48
  • 1
    Okay. So the `div` variable now refers to the `smart_div()` and not the original `div` function. Thanks. – give_it_a_bit Aug 12 '19 at 16:51
  • 1
    Objects dont "have names", names can refer to objects, but they are free to be re-assigned to different names at any time. – juanpa.arrivillaga Aug 12 '19 at 17:32
  • 2
    This topic is explained here very nicely: https://nedbatchelder.com/text/names.html – VPfB Aug 12 '19 at 17:54

2 Answers2

4

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.

Lianne
  • 108
  • 7
1

In Python everything (basically) is an object, and it does allow the re-use of variable names.

So I believe what you have done is to re-assign the variable name div from a name that pointed to a function, to a pointer to the function smart_div.

You should see that you are unable to access the old div function.

mgrollins
  • 641
  • 3
  • 9