Sub topic 8
Exploring objects with help(), dir(), and type()
This chapter assumes you can start the shell, read the echoed results of expressions, and recognize the >>> and ... prompts. It also assumes you know basic Python syntax and what a module is. If you can type import math and call math.sqrt(16), you are ready.
When you meet an unfamiliar value in the shell, you usually need three answers: what kind of thing it is, what it can do, and how to use it. Python has one built-in function for each. type() answers the first, dir() the second, and help() the third.
Asking what something is with type()
type(obj) returns the class of an object. The shell echoes that class using its repr, so you see <class '...'>.
>>> type(3)
<class 'int'>
>>> type(3.0)
<class 'float'>
>>> type("3")
<class 'str'>
>>> type([1, 2])
<class 'list'>
>>> type(None)
<class 'NoneType'>
>>> import math
>>> type(math)
<class 'module'>
>>> type(math.sqrt)
<class 'builtin_function_or_method'>
>>> type(type)
<class 'type'>The last line shows that classes are objects too, and that type is the class of classes.
The most common use of type() in a session is checking what a call actually returned. This matters when a value looks right but behaves oddly. "3" and 3 print the same way with print(), but "3" + 1 raises a TypeError. Calling type() on the suspect value settles it.
>>> value = input("number: ")
number: 42
>>> value
'42'
>>> type(value)
<class 'str'>
>>> int(value) + 1
43type() is for looking. In a program, use isinstance(obj, cls) for type checks, because it also accepts subclasses. type(True) == int is false, but isinstance(True, int) is true, since bool is a subclass of int.
>>> type(True)
<class 'bool'>
>>> isinstance(True, int)
TrueListing what an object offers with dir()
dir(obj) returns a sorted list of attribute names for an object. Attributes include methods, constants, and data. The names come back as strings, so the shell echoes a list of quoted names.
Called on a module, dir() lists everything the module defines.
>>> import math
>>> 'sqrt' in dir(math)
True
>>> [n for n in dir(math) if n.startswith('is')]
['isclose', 'isfinite', 'isinf', 'isnan', 'isqrt']Called on a value, dir() lists the attributes of its class, which are the methods you can call on it.
>>> [n for n in dir("abc") if n.startswith('is')]
['isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper']The list comprehension is a habit worth building. A raw dir("abc") prints more than seventy names, and nearly half are "dunder" names such as __add__ and __len__. Dunder is short for double underscore. These names are hooks that Python itself calls. For example, len(x) calls x.__len__(). They matter when you write your own classes, but they bury the useful names when you are browsing. Filtering out names that start with an underscore gives you the public interface.
>>> public = [n for n in dir(list) if not n.startswith('_')]
>>> public
['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']dir() with no argument
Called with no argument, dir() lists the names in your current scope. At the prompt, that is the module-level names of your session, which makes it a quick way to see what you have defined.
>>> x = 5
>>> def double(n):
... return n * 2
...
>>> 'x' in dir(), 'double' in dir()
(True, True)A fresh session also contains a few names that start with underscores, such as __name__ and __doc__. The exact set varies between Python versions, so test for the names you care about instead of comparing against a full list.
What dir() does not tell you
dir() shows names only. It does not say which are callable, what they return, or what arguments they take. To separate methods from plain data, combine it with callable().
>>> import string
>>> [n for n in dir(string) if not n.startswith('_') and callable(getattr(string, n))]
['Formatter', 'Template', 'capwords']The output also is not guaranteed to be complete. The documentation describes dir() as a convenience for interactive use. A class can define __getattr__ or __dir__ so that attributes exist without being listed, or are listed without being ordinary attributes. When you want only an instance's own stored data, vars(obj) returns its __dict__.
Reading documentation with help()
help(obj) shows the documentation Python holds for an object. It is built from the object's signature and its docstring, which is the string literal at the top of a function, class, or module.
>>> help(len)
Help on built-in function len in module builtins:
len(obj, /)
Return the number of items in a container.
The / in the signature means that the parameters before it are positional-only. You cannot write len(obj=[1, 2]).
Longer help text opens in a pager, a program that shows one screen at a time. Press the space bar for the next page, b to go back, / followed by text to search, and q to return to the >>> prompt. If you seem stuck after calling help(), you are still in the pager, so press q. Some environments, such as IDLE, print the text straight into the window and have no pager.
You can ask for help on a function, a class, a method, or a module.
>>> help(str.split)
>>> help(math)
>>> help(list)You can pass a string instead of an object. Python then looks the name up for you and imports the module if needed, so no earlier import is required.
>>> help('math.sqrt')
Help on built-in function sqrt in math:
math.sqrt = sqrt(x, /)
Return the square root of x.
The exact header lines differ a little between Python versions, but the signature and description are the useful parts.
Two forms need no object at all. help() with no argument starts an interactive help session with a help> prompt, where you type a name and leave with q. Strings such as help('keywords') and help('modules') list the reserved words and the importable modules. The modules listing can take a few seconds because Python scans what is installed.
Your own code is documented too
Anything you define at the prompt works with help(). A docstring becomes the description.
>>> def area(r):
... """Return the area of a circle with radius r."""
... return 3.14159 * r * r
...
>>> help(area)
Help on function area in module __main__:
area(r)
Return the area of a circle with radius r.
>>> area.__doc__
'Return the area of a circle with radius r.'The module name __main__ is how the shell labels code you typed in the session. Without a docstring, help() still shows the signature. This gives you a cheap check that Python recorded the parameters the way you intended.
If you only need the signature as an object, the standard library's inspect.signature(area) returns it.
Putting the three together
The three functions work best in sequence. You find out what you have, see what it offers, then read about the one method you need.
Here is a complete example. Suppose a call returned something and you do not know what to do with it.
>>> import os
>>> info = os.stat(".")
>>> type(info)
<class 'os.stat_result'>
>>> [n for n in dir(info) if n.startswith('st_') and not n.endswith('ns')][:4]
['st_atime', 'st_birthtime', 'st_blksize', 'st_blocks']
>>> help(os.stat_result)The names listed vary by operating system. For instance, st_birthtime is absent on some Linux builds. This is a good reminder that dir() reports what this object offers on this machine.
| Question | Tool | Typical call |
|---|---|---|
| What class is this value? | `type()` | `type(result)` |
| Is it an instance of a class or its subclasses? | `isinstance()` | `isinstance(x, int)` |
| What names does it have? | `dir()` | `dir(obj)` |
| What names are in my session? | `dir()` | `dir()` |
| What does it do and take? | `help()` | `help(obj.method)` |
| What is its stored instance data? | `vars()` | `vars(obj)` |
Common mistakes
Passing the result of a call instead of the function itself is the most frequent error. help(print) documents print. help(print()) runs print, which writes an empty line and returns None, so you get help on None.
>>> help(len())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: len() takes exactly one argument (0 given)Forgetting the import is the second one. dir(math) before import math raises NameError: name 'math' is not defined. Recent Python versions add a hint to the message, such as a suggestion to import the module. Either way, the session survives and you can import and retry.
A third mistake is reading dir() output as a promise. A name in the list does not mean the call will succeed with your arguments. Read the help text, then try it.
Exercise
In a fresh shell, you run import random and want to know whether the module has a function that picks several items from a list without repeats, and how to call it. Which three steps would you take, and what would each tell you?
Show answer
First, [n for n in dir(random) if not n.startswith('_')] lists the public names, and you look for a likely one such as sample. Second, type(random.sample) confirms it is a function or method rather than a constant. Third, help(random.sample) shows its signature, sample(population, k, *, counts=None), and its description. Then you test it, for example random.sample([1, 2, 3, 4], 2), which returns a list of two distinct items.
Exercise
What is the difference between help(len) and help(len([1, 2])), and what does the second one show?
Show answer
help(len) documents the function len. In help(len([1, 2])), Python first evaluates len([1, 2]), which is the integer 2, and then passes that value to help(). You get the documentation for the int class, not for len.