ZetCode

Python __getattribute__ Method

Last modified November 17, 2026 Python 3.15

__getattribute__ is called for every attribute access, before the normal lookup rules run. It is more powerful and more dangerous than __getattr__: every access, including to methods, passes through it, and a careless override recurses forever. This article shows logging, access control, virtual attributes, debugging, and combination with __setattr__.

Intercepting every access

Python evaluates obj.attr by calling type(obj).__getattribute__(obj, 'attr'). The default implementation performs the usual search. An override should call super().__getattribute__(attr) to delegate that work.

basic_getattribute.py
class Logger:
    def __init__(self, name):
        self.name = name

    def __getattribute__(self, attr):
        print("access", attr)
        return super().__getattribute__(attr)


obj = Logger("test")
print(obj.name)
try:
    print(obj.missing)
except AttributeError as e:
    print(type(e).__name__, e)

Both accesses are logged, including the failed one. The AttributeError message comes from the default implementation and is caught here. Calling super() is essential: reading anything through self inside the hook would trigger it again.

$ python basic_getattribute.py
access name
test
access missing
AttributeError 'Logger' object has no attribute 'missing'

Access control

The hook can reject names before lookup. Here attributes starting with an underscore are hidden from ordinary access. Because the check happens first, even methods with leading underscores would be blocked.

access_control.py
class Secure:
    def __init__(self):
        self.public = "open"
        self._secret = "confidential"

    def __getattribute__(self, attr):
        if attr.startswith("_"):
            raise AttributeError(f"{attr} is restricted")
        return super().__getattribute__(attr)


s = Secure()
print(s.public)
try:
    print(s._secret)
except AttributeError as e:
    print(type(e).__name__, e)
print(object.__getattribute__(s, "_secret"))

The public attribute is returned normally, while _secret raises the custom AttributeError. The final line bypasses the hook with object.__getattribute__ and reaches the value. This shows the scheme is a convention, not real security; the value is also reachable through the instance dictionary.

$ python access_control.py
open
AttributeError _secret is restricted
confidential

Virtual attributes

A name can be computed instead of stored. area is not an instance variable; the hook recognises the name and computes it from the radius retrieved through super().

virtual_attributes.py
import math


class Circle:
    def __init__(self, radius):
        self.radius = radius

    def __getattribute__(self, attr):
        if attr == "area":
            r = super().__getattribute__("radius")
            return math.pi * r ** 2
        return super().__getattribute__(attr)


c = Circle(5)
print(c.area)
print(c.radius)
print("area" in c.__dict__)

The computed area and the stored radius print as expected, and the last line confirms that area is absent from the instance dictionary. For a single computed value, a property is simpler and avoids intercepting every other attribute.

$ python virtual_attributes.py
78.53981633974483
5
False

Tracing where access happens

The inspect module can reveal the frame that triggered the access. Printing the caller's function name gives a stable, file-independent trace.

debugging.py
import inspect


class Debug:
    def __init__(self):
        self.x = 10
        self.y = 20

    def __getattribute__(self, attr):
        caller = inspect.currentframe().f_back
        print(f"{attr} read in {caller.f_code.co_name}")
        return super().__getattribute__(attr)


d = Debug()
print(d.x + d.y)

Both reads occur in the module body, shown as <module>, and their sum is printed afterwards. This technique can reveal unexpected attribute traffic, but it adds overhead to every access and should not be left in production code.

$ python debugging.py
x read in <module>
y read in <module>
30

Working with __setattr__

Read and write interception are separate hooks. The temperature class exposes a virtual fahrenheit attribute and converts assignments back to Celsius, delegating all other names to super().

combined.py
class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    def __getattribute__(self, attr):
        if attr == "fahrenheit":
            c = super().__getattribute__("celsius")
            return c * 9 / 5 + 32
        return super().__getattribute__(attr)

    def __setattr__(self, attr, value):
        if attr == "fahrenheit":
            super().__setattr__("celsius", (value - 32) * 5 / 9)
        else:
            super().__setattr__(attr, value)


t = Temperature(0)
print(t.fahrenheit)
t.fahrenheit = 212
print(t.celsius)

Reading the virtual attribute converts 0 degrees Celsius to 32.0 Fahrenheit; assigning 212 converts back to 100.0 Celsius. Using super().__setattr__ in the write hook avoids re-entering it, which assigning through self would do.

$ python combined.py
32.0
100.0

Best practices

Because this hook sees everything, keep it minimal:

Source

object.__getattribute__ - Python documentation

Customizing attribute access - Python documentation

Descriptor HowTo - Python documentation

In this article we have implemented the __getattribute__ method. We have covered logging, access control, virtual attributes, debugging, and cooperation with __setattr__. For related topics, see Python __getattr__ method, Python __setattr__ method, and Python getattr() function.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.