Python 3 reference · Built-in Functions
Python dir() Function
List the names an object has, such as attributes and methods. With no argument, list the names in the current scope.
Python 3 Since 3.0
Syntax
dir()
dir(object)
Parameters
| Parameter | Description |
|---|---|
object optional |
Any object: a module, class, instance, … |
Return value
A sorted list of names.
Examples
print([name for name in dir("text") if not name.startswith("_")][:8])
Output
['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find']
class Point:
def __init__(self):
self.x, self.y = 1, 2
def norm(self):
return (self.x ** 2 + self.y ** 2) ** 0.5
print([n for n in dir(Point()) if not n.startswith("__")])
Output
['norm', 'x', 'y']
import math
print([n for n in dir(math) if n.startswith("is")])
Output
['isclose', 'isfinite', 'isinf', 'isnan', 'isqrt']
Good to know
dir() is meant for exploring in the REPL. In programs, use hasattr(), getattr() or vars() instead.
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
vars()· Return the __dict__ of a module, class or object: its writable attributes as a dictionary. With no argument, like locals().hasattr()· Return True if an object has an attribute with the given name. It works by calling getattr() and catching AttributeError.help()· Show the built-in help for a function, class, module or keyword: its signature and documentation. Mostly used in the REPL.getattr()· Get an attribute by name, given as a string. An optional default is returned instead of raising AttributeError.- Python Modules and Imports · tutorial