ZetCode

Python __dir__ Method

Last modified November 17, 2026 Python 3.15

The dir() built-in lists the names an object offers, and the special method that supplies them is __dir__. Customizing it makes attributes created at runtime discoverable, hides implementation details, and changes what interactive shells and editors suggest. This article shows the dispatch, the default listing, and the common ways to extend it.

How dir() calls the hook

dir(obj) is evaluated as type(obj).__dir__(obj), and the built-in then sorts the returned iterable. Like other special methods, the lookup happens on the type, not on the instance, so assigning __dir__ to an object has no effect on dir(). Calling the method directly returns the names in the original order.

basic_dir.py
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        return f"Hi, I'm {self.name}"

    def __dir__(self):
        return ["name", "age", "greet"]


p = Person("Alice", 30)
print(dir(p))
print(p.__dir__())

p.__dir__ = lambda: ["fake"]
print(dir(p))

The hook lists exactly three names, so dir(p) contains no dunder names even though the object has a __dict__. The direct call shows the unsorted list, while dir() sorts it alphabetically. Assigning a replacement to the instance is ignored by dir() for the same reason that len(obj) ignores an instance-level __len__.

$ python basic_dir.py
['age', 'greet', 'name']
['name', 'age', 'greet']
['age', 'greet', 'name']

The default implementation

A class that does not define __dir__ inherits object.__dir__. It collects instance attributes from __dict__, names declared in __slots__, and attributes found on the class and its bases. That is why normal objects already list __class__, __dict__, and their methods without any extra work.

default_dir.py
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def norm(self):
        return (self.x ** 2 + self.y ** 2) ** 0.5


class SlotPoint:
    __slots__ = ("x", "y")

    def __init__(self, x, y):
        self.x = x
        self.y = y


pt = Point(3, 4)
print([n for n in dir(pt) if not n.startswith("__")])
print("norm" in dir(pt), "__class__" in dir(pt), "__dict__" in dir(pt))

sp = SlotPoint(3, 4)
print([n for n in dir(sp) if not n.startswith("__")])
print("__dict__" in dir(sp))

The Point instance exposes its two fields and its method, plus the usual dunder names. The SlotPoint has the two slot names but no __dict__, which the default implementation reflects. Filtering out names that begin with two underscores is a convenient way to see just the public surface.

$ python default_dir.py
['norm', 'x', 'y']
True True True
['x', 'y']
False

Adding dynamic names

Attributes produced by __getattr__ do not exist in __dict__, so the default listing cannot see them. The standard fix is to merge those names into super().__dir__(). A set removes duplicates, and sorting makes the result stable.

dynamic_dir.py
class Config:
    def __init__(self):
        self._settings = {"debug": False, "timeout": 30}

    def __dir__(self):
        base = super().__dir__()
        dynamic = [f"get_{k}" for k in self._settings]
        dynamic += [f"set_{k}" for k in self._settings]
        return sorted(set(base) | set(dynamic))

    def __getattr__(self, name):
        if name.startswith("get_"):
            key = name[4:]
            return lambda: self._settings.get(key)
        if name.startswith("set_"):
            key = name[4:]
            return lambda value: self._settings.update({key: value})
        raise AttributeError(name)


c = Config()
print([n for n in dir(c) if n.startswith(("get_", "set_"))])
print(c.get_debug())
c.set_timeout(60)
print(c.get_timeout())

The four generated names now appear in dir(c) and resolve to real callables. The listing follows the settings dictionary, so adding a new setting later needs no change to __dir__. This is what makes an object work well with tab completion in an interactive session.

$ python dynamic_dir.py
['get_debug', 'get_timeout', 'set_debug', 'set_timeout']
False
60

Hiding private attributes

The hook can also narrow the listing. Returning only the names that do not start with an underscore hides internal state from casual inspection and gives the object a cleaner public interface. This only changes what is advertised: the attributes are still reachable, so it must not be treated as a security measure.

hidden_dir.py
class SecureData:
    def __init__(self, public, secret):
        self.public_data = public
        self._secret_data = secret

    def __dir__(self):
        return [n for n in super().__dir__() if not n.startswith("_")]


sd = SecureData("Open info", "Top secret")
print(dir(sd))
print(sd._secret_data)

Only public_data is listed, and the direct access still works. Note that this implementation also drops dunder names such as __class__; if those should remain visible, keep names starting with two underscores in the filter.

$ python hidden_dir.py
['public_data']
Top secret

Combining with a base class

When a hierarchy customizes the listing at several levels, each override should extend the result of super().__dir__() rather than replace it. Otherwise a subclass silently discards what its parent advertised. In a multiple-inheritance chain the calls follow the normal method resolution order.

inherited_dir.py
class Base:
    def __dir__(self):
        return ["base_attr", "common_method"]


class Derived(Base):
    def __init__(self):
        self.derived_attr = "value"

    def __dir__(self):
        return sorted(set(super().__dir__()) | {"derived_attr", "new_method"})

    def new_method(self):
        pass


print(dir(Derived()))

The derived listing contains the two names from Base and the two added by Derived. The derived_attr value happens to be a real instance attribute, while new_method is a real method, but the hook does not check either claim; keeping the list in sync is the programmer's responsibility.

$ python inherited_dir.py
['base_attr', 'common_method', 'derived_attr', 'new_method']

Return values and errors

The hook should return an iterable of strings. A generator works because dir() consumes it and sorts the result; a string is iterated one character at a time, so "ab" is indistinguishable from a list of two names. A non-iterable return value raises TypeError, as does a class attribute that shadows the hook with None.

dir_errors.py
class GeneratorDir:
    def __dir__(self):
        return (name for name in ("b", "a"))


class StringDir:
    def __dir__(self):
        return "ab"


class IntListDir:
    def __dir__(self):
        return [3, 1, 2]


class IntDir:
    def __dir__(self):
        return 42


class NoDir:
    __dir__ = None


print(dir(GeneratorDir()))
print(dir(StringDir()))
print(dir(IntListDir()))

for cls in (IntDir, NoDir):
    try:
        dir(cls())
    except TypeError as e:
        print(cls.__name__, type(e).__name__, e)

The first two hooks produce the sorted names a and b. Python does not check that the items are strings: the integer list is sorted and returned as integers, which can confuse tools that expect names. A bare integer is not iterable and fails with a TypeError; setting __dir__ to None fails when dir() tries to call it.

$ python dir_errors.py
['a', 'b']
['a', 'b']
[1, 2, 3]
IntDir TypeError 'int' object is not iterable
NoDir TypeError 'NoneType' object is not callable

Best practices

A good __dir__ advertises what the object really supports without doing expensive work:

Source

object.__dir__ - Python documentation

dir() - Python documentation

Customizing attribute access - Python documentation

In this article we have implemented the __dir__ method. We have covered the dir() dispatch, the default listing, dynamic and hidden names, inheritance, and invalid return values. For related topics, see Python dir() function, Python introspection, Python __getattr__ method, and Python __getitem__ method.

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.