Is there a way to inspect the (differing) internal structures of Python objects that test as equal (==)?

StackOverflow https://stackoverflow.com/questions/1665176

  •  13-09-2019
  •  | 
  •  

Question

Yesterday I asked ("A case of outwardly equal lists of sets behaving differently under Python 2.5 (I think …)") why list W constructed as follows:

r_dim_1_based = range( 1, dim + 1)
set_dim_1_based =  set( r_dim_1_based)

def listW_fill_func( val):
    if (val == 0):
        return set_dim_1_based
    else:
        return set( [val])

W = [ listW_fill_func( A[cid])  
            for cid in r_ncells ]

didn't behave as I expected. In particular, it did not behave like other lists that showed equality with it (another_list == W --> True).

Is there a utility, trick, builtin, whatever that would have shown these differing internal structures to me? Something that would have produced perhaps a C-like declaration of the objects so that I would have seen at once that I was dealing with pointers in one case (list W) and values in the others?

Was it helpful?

Solution

You're dealing with references in each case (more similar to pointers than to values). You can surely introspect your objects' references to your heart's contents -- for example, if you have a list and want to check if any items are identical references,

if len(thelist) != len(set(id(x) for x in thelist)): ...

DO note that we're talking about references here -- so, two identical references to None, or two identical references to the int value 17, would also trigger the same alarm. Of course you can keep introspecting to remove that case, eliminating immutables from the list in a first pass, for example, if you think that multiple references to the same immutable are fine -- e.g.:

immutyps = int, long, float, tuple, frozenset, str, unicode
mutables = [x for x in thelist if not isinstance(x, immutyps)]
if len(mutables) != len(set(id(x) for x in mutables)):
  cryhavocandletloosethedogsofwar()

but I would question the return-on-investment of such a deep introspection strategy!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top