-2
def func(t):
    t = 5
    print('inside function', t)
    print('inside function address = ', id(hex(t)))

x = 3
func(x)
print('outside function',x)
print('outside function address = ', id(hex(x)))

This Prints

inside function 5
inside function address =  31255648
outside function 3
outside function address =  31255648

My understanding was a variable referenced in a function without assignment will use a variable outside of its scope. But if the function has an assignment, then it will create a new variable in a new space in memory and assign it there.

Why does the function id find the original address of the argument instead of the address of the newly created variable?

Akimbo
  • 63
  • 4
  • Are you sure you ran the code exactly as you provided it? Those results look strange. – gmds Mar 17 '19 at 08:16
  • `hex(x)` is a string. You're getting the `id` of a string, which is created and then immediately abandoned. Ids only need to be unique for the lifespan of their respective objects. Since the strings do not exist at the same time, they can have the same id. – khelwood Mar 17 '19 at 08:18
  • @PatrickArtner Uhhh, this has absolutely nothing to do with integer caching. All that's happening here is that a string is created, then destroyed, and then another string is created in the same memory location as the previous one. – Aran-Fey Mar 17 '19 at 08:19
  • Integers in python are caches if in range -5 to 255 or so - they got the same id regardless of where you use them from. you however are printing ids of stringvalues of the hex of int that you immediately throw away – Patrick Artner Mar 17 '19 at 08:20
  • @Aran-Fey yep - misread and fixedit again – Patrick Artner Mar 17 '19 at 08:20
  • `id` isn't strictly the memory address, but even when it is, it's the address on the heap, not the stack. This is nothing to do with the variable names. – Alex Hall Mar 17 '19 at 08:21

2 Answers2

1

hex(x) is a string. id(hex(x)) creates a string, gets its id, and then immediately discards the string.

IDs only need to be unique for the lifespan of their respective objects. Since the strings do not exist at the same time, they can have the same id.

khelwood
  • 55,782
  • 14
  • 81
  • 108
1

Your understanding of variable scopes is correct. But this behavior has nothing to do with scoping. In your analysis you've missed an important detail: You're not calling id(t); you're calling id(hex(t)).

This is what's happening, step by step:

  1. hex(5) is called. This creates the string '0x5' at the address 31255648.
  2. id(hex(5)) returns 31255648.
  3. The string is no longer needed and is garbage collected.
  4. hex(3) is called. This creates the string '0x3' at the address 31255648.
  5. id(hex(3)) returns 31255648.

In other words, you had two objects (strings) whose lifetimes didn't overlap and that just happened to be created at the same memory address, which is how they ended up having the same id.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149