Why does this code print a randomly selected attribute?

Viewed 283

Today while writing some especially terrible code, I stumbled across this mysterious behavior. The Python 3 program below prints a randomly selected attribute of object. How does this happen?

An obvious suspect for the nondeterminism is the random ordering of the vars(object) dictionary, but I can't see how that causes the observed behavior. One hypothesis I had was that it was caused by the ordering of __setattr__ being overridden, but this is disproved by the fact that the lambda is always called only once (checked by print debugging).

class TypeUnion: 
    pass

class t: 
    pass

def super_serious(obj):
    proxy = t()
    for name, val in vars(object).items():
        if not callable(val) or type(val) is type: 
            continue
        try: 
            setattr(t, name, lambda _, *x, **y: val)
        except AttributeError: 
            pass
    return proxy

print(super_serious(TypeUnion()).x)

N.B. The above program is not attempting to do anything useful; it is heavily reduced from the original.

3 Answers
Related