fork download
  1. def check_same(a, b):
  2. # Check whether the parameters passed to the function have the same or different IDs
  3. return(f'{id(a)} {id(b)} {"same" if id(a) == id(b) else "different"}')
  4.  
  5. import math
  6.  
  7. # Create 3 names, 2 of which refer to the same int object, with the other name referring to a different int object with the same values
  8. x = 1000 # Too large to be interned by CPython
  9. y = int(math.sqrt(1e6)) # Do it like this to prevent the compiler folding constants and making x and y the same object
  10. z = y # Make y the same object as z
  11.  
  12. print(f"Values: x={x} y={y} z={z}")
  13. print(f"id: x={id(x)} y={id(y)} z={id(z)}")
  14.  
  15. # Check whether, when a function is called with these objects, differences in object ID are preserved (pass-by-object-reference)
  16. # or lost (pass-by-value).
  17. # If ints were passed by value, then check_same would give "same" for all three pairs
  18. print(f"check_same(x, y): {check_same(x, y)}")
  19. print(f"check_same(x, z): {check_same(x, z)}")
  20. print(f"check_same(y, z): {check_same(y, z)}")
Success #stdin #stdout 0.03s 9636KB
stdin
Standard input is empty
stdout
Values: x=1000 y=1000 z=1000
id: x=22842200107280 y=22842198158448 z=22842198158448
check_same(x, y): 22842200107280 22842198158448 different
check_same(x, z): 22842200107280 22842198158448 different
check_same(y, z): 22842198158448 22842198158448 same