diveintopython.org
Python for experienced programmers

 

2.4. type, str, dir, and other built-in functions

Python has a small set of extremely useful built-in functions. All other functions are partitioned off into modules. This was actually a conscious design decision, to keep the core language from getting bloated like other scripting languages (cough cough, Visual Basic).

The type function returns the datatype of any arbitrary object. The possible types are listed in the types module. This is useful for helper functions which can handle several types of data.

Example 2.8. Introducing type

>>> type(1)           1
<type 'int'>
>>> li = []
>>> type(li)          2
<type 'list'>
>>> import odbchelper
>>> type(odbchelper)  3
<type 'module'>
>>> import types      4
>>> type(odbchelper) == types.ModuleType
1
1 type takes anything and returns its datatype. And I mean anything. Integers, strings, lists, dictionaries, tuples, functions, classes, modules, even types.
2 type can take a variable and return its datatype.
3 type also works on modules.
4 You can use the constants in the types module to compare types of objects. This is what the help function does, as we'll see shortly.

The str coerces data into a string. Every datatype can be coerced into a string.

Example 2.9. Introducing str

>>> str(1)          1
'1'
>>> horsemen = ['war', 'pestilence', 'famine']
>>> horsemen.append('Powerbuilder')
>>> str(horsemen)   2
"['war', 'pestilence', 'famine', 'Powerbuilder']"
>>> str(odbchelper) 3
"<module 'odbchelper' from 'c:\\docbook\\dip\\py\\odbchelper.py'>"
>>> str(None)       4
'None'
1 For simple datatypes like integers, you would expect str to work, because almost every language has a function to convert an integer to a string.
2 However, str works on any object of any type. Here it works on a list which we've constructed in bits and pieces.
3 str also works on modules. Note that the string representation of the module includes the pathname of the module on disk, so yours will be different.
4 A subtle but important behavior of str is that it works on None, the Python null value. It returns the string 'None'. We will use this to our advantage in the help function, as we'll see shortly.

At the heart of our help function is the powerful dir function. dir returns a list of the attributes and methods of any object: modules, functions, strings, lists, dictionaries… pretty much anything.

Example 2.10. Introducing dir

>>> li = []
>>> dir(li)           1
['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> d = {}
>>> dir(d)            2
['clear', 'copy', 'get', 'has_key', 'items', 'keys', 'setdefault', 'update', 'values']
>>> import odbchelper
>>> dir(odbchelper)   3
['__builtins__', '__doc__', '__file__', '__name__', 'buildConnectionString']
1 li is a list, so dir(li) returns a list of all the methods of a list. Note that the returned list contains the names of the methods as strings, not the methods themselves.
2 d is a dictionary, so dir(d) returns a list of the names of dictionary methods. At least one of these, keys, should look familiar.
3 This is where it really gets interesting. odbchelper is a module, so dir(odbchelper) returns a list of all kinds of stuff defined in the module, including built-in attributes, like __name__, and whatever other attributes and methods you define. In this case, odbchelper has only one user-defined method, the buildConnectionString function we studied in Chapter 1.

type, str, dir, and all the rest of Python's built-in functions are grouped into a special module called __builtins__. (That's two underscores before and after.) If it helps, you can think of Python automatically executing from __builtins__ import * on startup, which imports all the “built-in” functions into the namespace so you can use them directly.

The advantage of thinking like this is that you can access all the built-in functions and attributes as a group by getting information about the __builtins__ module. And guess what, we have a function for that; it's called help. Try it yourself and skim through the list now; we'll dive into some of the more important functions later. (Some of the built-in error classes, like AttributeError, should already look familiar.)

Example 2.11. Built-in attributes and functions

>>> from apihelper import help
>>> help(__builtins__, 20)
ArithmeticError      Base class for arithmetic errors.
AssertionError       Assertion failed.
AttributeError       Attribute not found.
EOFError             Read beyond end of file.
EnvironmentError     Base class for I/O related errors.
Exception            Common base class for all exceptions.
FloatingPointError   Floating point operation failed.
IOError              I/O operation failed.

[…snip…]
Note
Python comes with excellent reference manuals, which you should peruse thoroughly to learn all the modules Python has to offer. But whereas in most languages you would find yourself referring back to the manuals (or man pages, or, God help you, MSDN) to remind yourself how to use these modules, Python is largely self-documenting.