Is there some introspection method allowing to reliably obtain the underlying data structure of an object instance, that is unaffected by any customizations?
In Python 3 an object's low-level implementation can be deeply obscured: Attribute lookup can be customized, and even the __dict__
and __slots__
attributes may not give a full picture, as they are writeable. dir()
is explicitly meant to show "interesting" attributes rather than actual attributes, and even the inspect
module doesn't seem to provide such functionality.
Not a duplicate. This question has been flagged as duplicate of Is there a built-in function to print all the current properties and values of an object?. However, that other question only talks about the standard ways of introspecting classes, which here are explicitly listed as not reliable on a lower level.
As an example consider the following script with an intentionally obscured class.
import inspectactual_members = None # <- For showing the actual contents later.class ObscuredClass:def __init__(self):global actual_membersactual_members = dict()self.__dict__ = actual_membersself.actual_field = "actual_value"def __getattribute__(self, name):if name == "__dict__":return { "fake_field": "fake value - shown in __dict__" }else:return "fake_value - shown in inspect.getmembers()"obj = ObscuredClass()
print(f"{actual_members = }")
print(f"{dir(obj) = }")
print(f"{obj.__dict__ = }")
print(f"{inspect.getmembers(obj) = }")
which produces the output
actual_members = {'actual_field': 'actual_value'}
dir(obj) = ['fake_field']
obj.__dict__ = {'fake_field': 'fake value - shown in __dict__'}
inspect.getmembers(obj) = [('fake_field', 'fake_value - shown in inspect.getmembers()')]