Sub topic 8
Exploring objects with help(), dir(), and type()
This chapter assumes you can start the shell, evaluate expressions, and import a module. When you meet an unfamiliar object, the shell can tell you what it is, what it can do, and how to use it. You don't need to leave for a browser. Three built-in functions cover most of this.
The three questions
| Function | Question it answers | Returns |
|---|---|---|
| `type(obj)` | What kind of object is this? | A class |
| `dir(obj)` | What names can I use on it? | A sorted list of strings |
| `help(obj)` | How do I use it? | Prints documentation |
type(): confirm what you have
Calling type() is the quickest way to check what a call returned. This matters because the echo can hide differences. The values 4.0 and 4 look alike, but they are different classes.
>>> import math
>>> math.sqrt(16)
4.0
>>> type(math.sqrt(16))
<class 'float'>
>>> type(math)
<class 'module'>
>>> type(math.sqrt)
<class 'builtin_function_or_method'>Everything in Python is an object, including modules and functions, so type() works on all of them.
dir(): list the available names
dir() returns the names of an object's attributes and methods. Use it on a module to see its contents, or on a value to see its methods.
>>> import math
>>> 'sqrt' in dir(math)
True
>>> 'upper' in dir("hello")
True
>>> [name for name in dir("hello") if not name.startswith("_")][:5]
['capitalize', 'casefold', 'center', 'count', 'encode']The raw output of dir() is long. It includes names that begin and end with double underscores, such as __len__. These are special methods that Python calls for you. Filtering them out with a list comprehension, as above, leaves the names you usually call yourself.
Called with no argument, dir() lists the names in your current session. This is a quick way to see which variables you have defined.
help(): read the documentation
help() shows the docstring (the documentation text attached to an object) and the signature, which is the list of parameters.
>>> help(math.sqrt)
Help on built-in function sqrt in module math:
sqrt(x, /)
Return the square root of x.
You can pass a function, a module, a class, or a method. Two forms are worth remembering:
help("str.split")looks an item up by name, which is useful when you don't have an object to pass.help()with no argument starts an interactive help session. Typequitto return to the normal prompt.
For long output, such as help(str), the shell opens a pager. Press space to move down a page and q to quit.
Putting them together
Suppose you receive an object from a call and don't know what it is. Work through it in order.
>>> import os
>>> info = os.stat(".")
>>> type(info)
<class 'os.stat_result'>
>>> 'st_size' in dir(info)
True
>>> isinstance(info.st_size, int)
TrueHere type() names the class, dir() confirms the attribute st_size exists, and a final check shows it holds an integer. If you need to know what the attribute means, help(os.stat_result) has the details.
Common errors
- Forgetting that
help(len())calls the function. Writehelp(len), without parentheses, to pass the function itself. - Misreading
dir()output. A name in the list may be a method or a plain value. Usetype(getattr(obj, name))orcallable()to tell them apart. - Getting stuck in the pager. Press
q.
Exercise
You run data = some_function() and the shell prints nothing. Using only the three functions from this chapter, how do you find out what data holds and whether it has an append method?
Show answer
Run type(data) to see its class (it may be NoneType, since the shell does not echo None). Then run 'append' in dir(data) to check for the method. If it is present, help(data.append) shows how to call it.