dir() and help() Explore Any Python Object from the REPL
Python's built-in functions (BIFs) need no import. Three of them answer most "what can this object do?" questions without leaving the interpreter: type() says what it is, dir() lists its attributes and methods, and help() shows their documentation.
Inspecting an Object
deck = set()
type(deck) # <class 'set'>
dir(deck) # ['__and__', ..., 'add', 'clear', 'difference', 'pop', 'union', ...]
help(deck.add) # docstring of set.add
len({"Tom", "Jim"}) # 2
Reading dir() Output
- Names with double underscores (
__len__,__contains__) are special methods: they power built-ins and operators.__len__is whylen(deck)works;__contains__is whyx in deckworks. - The plain names (
add,union,discard) are the methods meant for direct use.
Other Built-ins Worth Knowing
| Function | Returns |
|---|---|
len(x) |
number of items |
isinstance(x, T) |
whether x is a T (or a subclass) |
vars(obj) |
the instance's attribute dictionary |
sorted(x) |
a new sorted list |
enumerate(x) |
(index, item) pairs |
References
- Programming Languages MOC - hub for language notes.
- Python documentation: Built-in Functions - the full list.
- Python documentation: Special method names - what the dunder methods do.
Review cards
Flashcard Why does len(deck) work on a set?
Sets define the special method len, which len() calls; dir(deck) lists it among the dunder methods. contains likewise makes x in deck work.