My initial goal was to create a function which will print the type and memory address of the given object. To be as most universal as possible I wanted also include the variable name, something like this:
>>> a=10
>>> print type_addr(a)
a: int, 0x13b8080
For this purpose I need to know the name of an variable passed to this function. This page suggest following code (It a little bit modified version but the idea remain the same, iterate over locals().iteritems()
. I know it is not safe and it has several pitfalls mentioned on given link but my plans was to improve it):
#!/usr/bin/python
a = b = c = 10
b = 11
for k, v in list(locals().iteritems()):
if v is b:
# if id(v) == id(b):
print "k: %s" % k
print "v: %s" % v
print "a: %s" % hex(id(k))
Output of above code is:
k: b
v: 11
a: 0x7fece0f305f8
My next goal was to make subroutine which will give me desired result, so I've tried to wrap it into subroutine:
#!/usr/bin/python
a = b = c = 10
b = 11
def addr_type(obj):
for k, v in list(locals().iteritems()):
# if id(v) == id(a):
if v is obj:
print "k: %s" % k
print "v: %s" % v
print "a: %s" % hex(id(k))
for k, v in list(locals().iteritems()):
if v is b:
# if id(v) == id(b):
print "k: %s" % k
print "v: %s" % v
print "a: %s" % hex(id(k))
print "#################"
addr_type(b)
The output of above code is:
k: b
v: 11
a: 0x7fc9253715f8
#################
k: obj
v: 11
a: 0x7fc9253198a0
As you can see, neither the name of variable nor the address are the same. Then I started to dig deeper and tried following:
#!/usr/bin/python
a = b = c = 10
b = 11
for k, v in list(locals().iteritems()):
print "k: %s" % k
print "v: %s" % v
print "a: %s" % hex(id(k))
print "##############"
if a is b:
print "a and b is the same objects"
else:
print "a and b is NOT the same objects"
if a is c:
print "a and c is the same objects"
else:
print "a and c is NOT the same objects"
if b is c:
print "b and c is the same objects"
else:
print "b and c is NOT the same objects"
Which returned:
k: a
v: 10
a: 0x7ff07d54b5d0
##############
k: c
v: 10
a: 0x7ff07d54bbe8
##############
k: b
v: 11
a: 0x7ff07d54b5f8
##############
<Some loaded modules here but nothing interesting>
##############
a and b is NOT the same objects
a and c is the same objects
b and c is NOT the same objects
Questions:
- How to rewrite the working code and make the function that will print the name of passed variable?
- Why the same objects have different addresses?