Python dir() Function: Syntax and 5 Examples

If you want to see an object’s names in Python, the Python dir function does exactly that. It takes an optional object and gives you back a sorted list of its names.

print(dir([])[-3:])
# ['remove', 'reverse', 'sort']

In this tutorial, I’ll walk through its syntax and five examples that go from your local scope to modules and your own classes. I ran every one in Python 3.12.5 from Command Prompt.

Python dir() Syntax

dir()
dir(object, /)
ParameterRequiredDefaultDescription
objectNononeAny module, class, instance or value to inspect

Return value: a list of strings in alphabetical order. With no argument, you get the names in the current local scope.

Note: dir in Python is a built-in function, not a method. It sits with the other Python built-in functions.

When to Use dir() in Python

  • Checking which methods a string, list or dict offers
  • Exploring an unfamiliar module in the REPL or Jupyter
  • Debugging an AttributeError typo
  • Seeing which variables exist inside a function

That last one ties into how variable scope works in Python.

Example 1: What Does dir() Return Without an Argument?

Let me start with a bare call inside a function and at the top level:

city = "Austin"

def checkout(price, qty):
    tax = 0.0825
    print(dir())

checkout(19.99, 3)
print([n for n in dir() if not n.startswith("_")])

Output:

['price', 'qty', 'tax']
['checkout', 'city']
Python dir function with no argument listing local names inside a function and at module level in Command Prompt
Local names first, then module names.

How does this work? Inside checkout(), dir() listed only the parameters and tax. At module level, the filter dropped the dunder names and left checkout and city.

Example 2: List the Methods of a String or List with dir()

Python strings carry many special names, so filter out anything starting with an underscore:

public = [m for m in dir(str) if not m.startswith("_")]
print(len(dir(str)), "names,", len(public), "public")
print(public[:6])
print([m for m in dir(list) if not m.startswith("_")])

Output:

81 names, 47 public
['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith']
['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
Python dir on str and list showing the count of names and the public methods in Command Prompt
Public names only.

How does this work? dir(str) returned 81 names, and 47 are public methods like capitalize. I used the Python len() function to count them.

Example 3: Inspect a Python Module with dir()

Modules work the same way. Here, I’ll search the math module for logarithm functions:

import math

print([n for n in dir(math) if "log" in n])
print("isqrt" in dir(math))

Output:

['log', 'log10', 'log1p', 'log2']
True

How does this work? The comprehension kept the four math names containing “log”. Read more in my Python math module tutorial.

Example 4: Use dir() on a Custom Class Object

On an instance, dir() shows instance data, class attributes and methods together:

class Invoice:
    tax_rate = 0.07

    def __init__(self, number, amount):
        self.number = number
        self.amount = amount

    def total(self):
        return round(self.amount * (1 + self.tax_rate), 2)

inv = Invoice("INV-2026-118", 249.99)
print([n for n in dir(inv) if not n.startswith("_")])
print(vars(inv))

Output:

['amount', 'number', 'tax_rate', 'total']
{'number': 'INV-2026-118', 'amount': 249.99}
Python dir on a custom Invoice object compared with vars in Command Prompt
dir() vs vars() on one object.

How does this work? dir(inv) mixed instance values, the class attribute tax_rate and the method total. vars() kept only instance data.

See the difference between dir() and vars() in Python and the Python __dict__ attribute.

Example 5: Separate Methods from Attributes with callable()

Pair it with getattr() and callable() to split a date’s names:

from datetime import date

ship = date(2026, 11, 27)
names = [n for n in dir(ship) if not n.startswith("_")]

values = [n for n in names if not callable(getattr(ship, n))]
methods = [n for n in names if callable(getattr(ship, n))]
print("Values:", values)
print("Methods:", len(methods), methods[:4])

Output:

Values: ['day', 'max', 'min', 'month', 'resolution', 'year']
Methods: 14 ['ctime', 'fromisocalendar', 'fromisoformat', 'fromordinal']
Python dir with getattr and callable separating values from methods on a date object in Command Prompt
Values vs methods.

How does this work? getattr() fetched each name, and callable() was True for methods like ctime. Values like year landed first.

Pro Tip: see the Python callable() function and getattr() and setattr().

Common Mistakes with Python dir()

These Python dir() surprises are the ones you’ll likely hit (more in types of errors in Python):

class Config:
    def __getattr__(self, name):
        return "default"

class Broken:
    def __dir__(self):
        return None

print("region" in dir(Config()), Config().region)
print("mro" in dir(int), int.mro())

for expr in ['dir(1, 2)', '"hi".uppercase()', 'dir(Broken())']:
    try:
        eval(expr)
    except (TypeError, AttributeError) as err:
        print(f"{type(err).__name__}: {err}")

Output:

False default
False [<class 'int'>, <class 'object'>]
TypeError: dir expected at most 1 argument, got 2
AttributeError: 'str' object has no attribute 'uppercase'
TypeError: 'NoneType' object is not iterable
Common Python dir mistakes: getattr names, metaclass methods, two arguments, typo and bad __dir__
Five dir() gotchas.
  1. Names from __getattr__() don’t appear.
  2. Classes skip metaclass methods like mro.
  3. dir() takes one argument at most.
  4. Use dir() to spot attribute typos.
  5. __dir__() must return an iterable.

Wrapping Up the Python dir() Function

Python’s dir() function lists the names in a scope or on any object. Filter out dunder names and add getattr() for values. In VS Code, IntelliSense shows the same list.

Next, browse more Python built-in functions and methods.

You might like these too:

Python dir() Function: Common Questions

What does dir do in Python?

It returns the names an object has, or the names in your current scope.

What’s the difference between dir() and help()?

dir() lists names; help() prints their documentation.

Does dir() show private attributes?

Yes. Names starting with _ appear unless __dir__() hides them.

Is the dir() list sorted?

Yes. It’s always in alphabetical order.

Does dir() list every attribute?

Not always; it aims for useful names. See dir() in the Python docs.