Python dir() function
List the names (attributes and methods) an object has.
Syntax
dir(obj)
Great for exploring: dir(str) lists every string method. Names starting with underscores are internal; filter them out.
Parameters
| obj | any object or module |
Return value
a sorted list of names
Example
Code
methods = [m for m in dir("text") if not m.startswith("_")] print(len(methods), "string methods, for example:", methods[:8]) import math print([n for n in dir(math) if n.startswith("s")])
Output
47 string methods, for example: ['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find'] ['sin', 'sinh', 'sqrt', 'sumprod']
Related
Learn it step by step in the free lesson Modules & the Standard Library, with exercises that check your answers.