Yandex

Python dir() Function – List Attributes of Objects



Python dir() Function

The dir() function is a built-in Python tool that returns a list of valid attributes (including methods) for any object. It's often used for exploring objects during development or debugging.

Syntax

dir([object])

Parameters:

  • object (optional) – the object whose attributes you want to list

Returns:

  • A list of strings – each representing a valid attribute name of the object

Example 1: Using dir() without Arguments

When used without arguments, dir() returns the names in the current local scope.

x = 10
y = "hello"
print(dir())
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'x', 'y']

Example 2: Using dir() with a Built-in Object

print(dir("hello"))

Output (partial):

['__add__', '__class__', '__contains__', 'capitalize', 'casefold', 'center', 'count', ...]

This shows all the string methods and internal attributes.

Example 3: Using dir() with a Module

import math
print(dir(math))

Output (partial):

['__doc__', '__loader__', 'acos', 'asin', 'atan', 'ceil', 'cos', 'pi', 'sqrt', ...]

Use Cases of dir()

  • Exploring unknown objects or modules during development
  • Quick introspection without reading documentation
  • Understanding what operations can be done on an object

Common Mistakes

  • Not all returned items are methods – some are special/internal attributes
  • dir() doesn't always list everything – some attributes added via __getattr__ may not appear

Interview Tip

Use dir() along with type() and help() for debugging and exploring unfamiliar objects during coding interviews or while using third-party libraries.

Summary

  • dir() helps inspect available attributes and methods of objects
  • With no arguments, it shows names in the current local scope
  • It's useful for exploring built-in types, custom classes, and modules

Practice Task

Try running dir() on a few different objects like [], {}, set(), and len. Observe how their available methods and properties differ.

print("List Methods:", dir([]))
print("Dict Methods:", dir({}))
print("Set Methods:", dir(set()))
print("Function Methods:", dir(len))


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M