开发者

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

开发者 https://www.devze.com 2022-12-09 22:18 出处:网络
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:

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 i开发者_如何转开发n one case (list W) and values in the others?


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消