Python dir() Function: A Practical Guide With Examples

When I build a small reporting script, I often receive an unfamiliar object from a library, API response, or custom class. I need to know what that object contains before I can use it safely. Rather than guessing method names or digging through code first, I use the Python dir() function.

The dir() function gives you a quick list of names available on an object. Those names may include methods, attributes, built-in features, and values you created yourself. It is one of the most useful inspection tools for debugging, learning a new module, and exploring Python objects interactively.

This practical Python tutorial shows how to use the Python dir() function with variables, lists, strings, modules, custom classes, and real debugging examples.

What Is the Python dir() Function?

The dir() function is a built-in Python function that returns a list of names available in the current scope or on a specific object.

In simple terms, it answers this question:

“What can I access or use with this Python object?”

The returned list usually includes:

  • Attributes: Values stored on an object, such as name, price, or status
  • Methods: Functions attached to an object, such as append(), upper(), or replace()
  • Special methods: Python’s internal methods, such as __init__, __str__, and __len__
  • Inherited members: Features received from a parent class

The basic syntax is:

dir([object])

The square brackets mean the object is optional.

  • Use dir() without an argument to inspect the current Python scope.
  • Use dir(object) to inspect a specific object.

The function works in Python 3, including Python 3.10, 3.11, 3.12, and newer versions.

Python dir() Function Syntax

Here is the basic form:

dir()

Or:

dir(object_name)

The object_name can be almost anything in Python:

  • A string
  • A list
  • A dictionary
  • A module
  • A function
  • A class
  • An instance of a class
  • A built-in data type

For example, if you are working with a list of sales amounts, you can inspect its available methods before writing your processing logic.

monthly_sales = [1200, 1450, 980, 1750]

print(dir(monthly_sales))

Sample output:

['__add__', '__class__', '__class_getitem__', '__contains__',
'__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__getitem__',
'__gt__', '__hash__', '__iadd__', '__imul__', '__init__',
'__init_subclass__', '__iter__', '__le__', '__len__', '__lt__',
'__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__reversed__', '__rmul__', '__setattr__',
'__setitem__', '__sizeof__', '__str__', '__subclasshook__',
'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']

You can refer to the screenshot below to see the output.

Python dir() Function

The output differs slightly across Python versions. However, common list methods such as append, remove, sort, and pop remain available.

If you want to learn those list methods in depth, see this guide on how to add elements to an empty Python list and this tutorial to sort a list in Python without using the sort function.

Use Python dir() Without an Argument

When you call dir() without an argument, Python returns names available in your current scope.

A scope is the area of your program where a variable, function, or class name exists. For example, variables created at the top of a script belong to the global scope.

Here is a simple example.

employee_name = "Emily Johnson"
department = "Finance"
monthly_target = 25000

print(dir())

Sample output:

['__annotations__', '__builtins__', '__cached__', '__doc__',
'__file__', '__loader__', '__name__', '__package__', '__spec__',
'department', 'employee_name', 'monthly_target']

You can refer to the screenshot below to see the output.

dir() Function Python

Python includes several special names that begin and end with double underscores. These are often called dunder names, short for “double underscore” names.

The important part of the output is your own variables:

'department'
'employee_name'
'monthly_target'

This approach helps when you are working in the Python shell, Jupyter Notebook, or an IDE console and want to confirm which variables are available.

Filter Your Own Names From dir()

The default output includes Python’s internal names. You can filter them out and show only names that do not begin with an underscore.

employee_name = "Emily Johnson"
department = "Finance"
monthly_target = 25000

available_names = [name for name in dir() if not name.startswith("_")]

print(available_names)

Sample output:

['department', 'employee_name', 'monthly_target']

This uses a list comprehension, which is a compact way to create a new list from another sequence. The condition removes names that start with _.

This pattern is useful in automation scripts where you need to inspect variables during development. If you are new to list processing, you may also find this guide helpful on how to filter lists in Python.

Use the Python dir() Function With Strings

Strings include many built-in methods for cleaning, formatting, splitting, and checking text. I use dir() on strings when I remember that Python has a feature but cannot remember its exact name.

For example, imagine a customer-support report that contains employee names in inconsistent letter cases.

customer_name = "michael brown"

string_methods = [name for name in dir(customer_name) if not name.startswith("_")]

print(string_methods)

Sample output:

['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith',
'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum',
'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier',
'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle',
'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans',
'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind',
'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split',
'splitlines', 'startswith', 'strip', 'swapcase', 'title',
'translate', 'upper', 'zfill']

Now you can spot useful methods such as title(), strip(), and replace().

Here is a practical example that uses those methods.

customer_name = "  michael brown  "

clean_name = customer_name.strip().title()

print(clean_name)

Sample output:

Michael Brown

The strip() method removes extra spaces from the beginning and end. The title() method changes the first letter of each word to uppercase.

For more practical string work, see how to remove spaces from a string in Python and convert a string to lowercase in Python.

Use Python dir() With Lists

Lists are common in reporting scripts, data-cleaning tasks, and file-processing automation. The Python dir() function helps you discover the available operations without memorizing every list method.

Here is an example with a weekly order list.

weekly_orders = ["Laptop", "Monitor", "Keyboard", "Mouse"]

list_methods = [name for name in dir(weekly_orders) if not name.startswith("_")]

print(list_methods)

Sample output:

['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']

You can refer to the screenshot below to see the output.

dir() Function in Python

Suppose you notice the append and sort methods in the output. You can use them to update your list.

weekly_orders = ["Laptop", "Monitor", "Keyboard", "Mouse"]

weekly_orders.append("Webcam")
weekly_orders.sort()

print(weekly_orders)

Sample output:

['Keyboard', 'Laptop', 'Monitor', 'Mouse', 'Webcam']

You can use the same inspection approach before working with a list from a CSV file, a database query, or an API response.

Pro Tip: I have found that dir() saves time when I switch between data types. A method that works on a list, such as append(), does not work on a string. Checking dir() first helps me avoid avoidable AttributeError messages.

Use Python dir() With Dictionaries

A dictionary stores data as key-value pairs. It works well for employee records, product details, JSON data, and application settings.

For example, a reporting script may store a sales representative’s details in a dictionary.

sales_rep = {
"name": "Daniel Carter",
"region": "Texas",
"monthly_sales": 18450
}

dictionary_methods = [name for name in dir(sales_rep) if not name.startswith("_")]

print(dictionary_methods)

Sample output:

['clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop',
'popitem', 'setdefault', 'update', 'values']

The output tells you that dictionaries support methods such as get(), items(), keys(), and update().

Here is how you can use get() safely.

sales_rep = {
"name": "Daniel Carter",
"region": "Texas",
"monthly_sales": 18450
}

sales_target = sales_rep.get("monthly_target", 20000)

print(sales_target)

Sample output:

20000

The get() method returns the value for a key. If the key does not exist, it returns the default value you provide instead of causing an error.

You can explore dictionaries further by learning how to check whether a key exists in a Python dictionary or update dictionary values in Python.

Use Python dir() With Modules

A module is a Python file or built-in package that contains reusable code. Modules help you organize functions, classes, and constants.

For example, the built-in math module includes functions for calculations. You can inspect it with dir().

import math

math_items = [name for name in dir(math) if not name.startswith("_")]

print(math_items)

Sample output:

['acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil',
'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'exp',
'factorial', 'floor', 'fmod', 'fsum', 'gcd', 'hypot', 'inf', 'isclose',
'isfinite', 'isinf', 'isnan', 'lcm', 'ldexp', 'lgamma', 'log', 'log10',
'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod',
'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau',
'trunc', 'ulp']

Now you know that the module contains ceil, floor, sqrt, and factorial.

Here is a simple reporting example that rounds an average order value up to the next whole dollar.

import math

average_order_value = 124.25
rounded_value = math.ceil(average_order_value)

print(rounded_value)

Sample output:

125

If you need more details about numeric helpers, explore the ceil function in Python and the floor function in Python.

Use Python dir() With Custom Classes

A class is a blueprint for creating objects. An object stores related data and behavior in one place.

In real projects, I often use dir() to inspect objects from custom classes. This is especially useful when a teammate creates a class, when a library returns an object, or when you revisit code after several months.

Here is a complete example for a local sales-reporting tool.

class SalesReport:
report_type = "Monthly Sales"

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

def format_summary(self):
return f"{self.representative} generated ${self.amount:,} in sales."

def meets_target(self, target):
return self.amount >= target


report = SalesReport("Olivia Davis", 28450)

class_items = [name for name in dir(report) if not name.startswith("_")]

print(class_items)

Sample output:

['amount', 'format_summary', 'meets_target', 'report_type', 'representative']

The output includes:<