dir() and help() Explore Any Python Object from the REPL

In progress

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 why len(deck) works; __contains__ is why x in deck works.
  • 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

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.