You are here: Home > Dive Into Python > The Power Of Introspection > type, str, dir, and other built-in functions | << >> | ||||
Dive Into PythonPython for experienced programmers |
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.
>>> type(1) <type 'int'> >>> li = [] >>> type(li) <type 'list'> >>> import odbchelper >>> type(odbchelper) <type 'module'> >>> import types >>> type(odbchelper) == types.ModuleType 1
The str coerces data into a string. Every datatype can be coerced into a string.
>>> str(1) '1' >>> horsemen = ['war', 'pestilence', 'famine'] >>> horsemen.append('Powerbuilder') >>> str(horsemen) "['war', 'pestilence', 'famine', 'Powerbuilder']" >>> str(odbchelper) "<module 'odbchelper' from 'c:\\docbook\\dip\\py\\odbchelper.py'>" >>> str(None) 'None'
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.
>>> li = [] >>> dir(li) ['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] >>> d = {} >>> dir(d) ['clear', 'copy', 'get', 'has_key', 'items', 'keys', 'setdefault', 'update', 'values'] >>> import odbchelper >>> dir(odbchelper) ['__builtins__', '__doc__', '__file__', '__name__', 'buildConnectionString']
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. | |
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. | |
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 __doc__, and whatever other attributes and methods you define. In this case, odbchelper has only one user-defined method, the buildConnectionString function we studied in Getting To Know Python. |
Finally, the callable function takes any object and returns 1 if the object can be called, or 0 otherwise. Callable objects include functions, class methods, even classes themselves. (More on classes in chapter 3.)
>>> import string >>> string.punctuation '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' >>> string.join <function join at 00C55A7C> >>> callable(string.punctuation) 0 >>> callable(string.join) 1 >>> print string.join.__doc__ join(list [,sep]) -> string Return a string composed of the words in list, with intervening occurrences of sep. The default separator is a single space. (joinfields and join are synonymous)
The functions in the string module are deprecated (although lots of people still use the join function), but the module contains lots of useful constants like this string.punctuation, which contains all the standard punctuation characters. | |
string.join is a function that joins a list of strings. | |
string.punctuation is not callable; it is a string. (A string does have callable methods, but the string itself is not callable.) | |
string.join is callable; it’s a function that takes two arguments. | |
Any callable object may have a doc string. Using the callable function on each of an object’s attributes, we can determine which attributes we care about (methods, functions, classes) and which we want to ignore (constants, etc.) without knowing anything about the object ahead of time. |
type, str, dir, and all the rest of Python’s built-in functions are grouped into a special module called __builtin__. (That’s two underscores before and after.) If it helps, you can think of Python automatically executing from __builtin__ 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 __builtin__ 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.)
>>> from apihelper import help >>> import __builtin__ >>> help(__builtin__, 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...]
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. |
<< Optional and named arguments |
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | |
Getting object references with getattr >> |