How on earth do you SAFELY lookup an attribute, without triggering either the class OR the metaclass’s __getattribute__
method?
object.__getattribute__
, a function I believed to be totally safe, is raising an AttributeError:
Traceback (most recent call last):
File "C:GitHubPyKotorLibrariesUtilitysrcutilitytricks.py", line 49, in update_class_instances
if isinstance(obj, old_class):
File "C:GitHubPyKotorLibrariesUtilitysrcutilitysystempath.py", line 104, in __instancecheck__
return cls.__subclasscheck__(instance.__class__)
File "C:GitHubPyKotorLibrariesUtilitysrcutilitysystempath.py", line 107, in __subclasscheck__
return pathlib_to_override(cls) in pathlib_to_override(subclass).__mro__
File "C:GitHubPyKotorLibrariesUtilitysrcutilitylogger_util.py", line 471, in __getattribute__
return getattr(instance, attr_name)
File "C:GitHubPyKotorLibrariesUtilitysrcutilitylogger_util.py", line 524, in __getattribute__
if isinstance(e, AttributeError) and object.__getattribute__(self, "__getattr__") is not None:
AttributeError: 'ExampleClass' object has no attribute '__getattr__'
So naturally I then tried type.__getattribute__
. Result:
Traceback (most recent call last):
File "C:GitHubPyKotorLibrariesUtilitysrcutilitytricks.py", line 83, in debug_reload_pymodules
update_class_instances(old_attribute, new_attribute)
File "C:GitHubPyKotorLibrariesUtilitysrcutilitytricks.py", line 52, in update_class_instances
RobustRootLogger.exception(f"Error updating class '{old_class.__class__.__name__}'")
File "C:GitHubPyKotorLibrariesUtilitysrcutilitylogger_util.py", line 471, in __getattribute__
return getattr(instance, attr_name)
File "C:GitHubPyKotorLibrariesUtilitysrcutilitylogger_util.py", line 524, in __getattribute__
if isinstance(e, AttributeError) and type.__getattribute__(our_type, "__getattr__") is not None:
AttributeError: type object 'ExampleClass' has no attribute '__getattr__'
Related links:
Python: Can a class forbid clients setting new attributes?
Python 3 – Check class attribute without calling __getattr__
Is there a 100% safe way to lookup attributes on a python object and/or type, without wrapping in a try-catch? Thank you for taking the time to read my newbie question!
Note The code I’m writing is diving deep into the internals of Python, and due to its nature is bound to cause weird random issues such as this (i’m experimenting with importlib
, __import__
, and sys.modules
. Since it is not related to the question I’m not going to clutter the thread with that code.