13.3 Internal TypesSome of the internal Python objects that I mention in this section are hard to use. Using such objects correctly requires some study of Python's own C (or Java) sources. Such black magic is rarely needed, except to build general-purpose development frameworks and similar wizardly tasks. Once you do understand things in depth, Python empowers you to exert control, if and when you need to. Since Python exposes internal objects to your Python code, you can exert that control by coding in Python, even when a nodding acquaintance with C (or Java) is needed to understand what is going on. 13.3.1 Type ObjectsThe built-in type named type acts as a factory object, returning objects that are types themselves (type was a built-in function in Python 2.1 and earlier). Type objects don't need to support any special operations except equality comparison and representation as strings. Most type objects are callable, and return new instances of the type when called. In particular, built-in types such as int, float, list, str, tuple, and dict all work this way. The attributes of the types module are the built-in types, each with one or more names. For example, types.DictType and types.DictionaryType both refer to type({ }), also known since Python 2.2 as the built-in type dict. Besides being callable to generate instances, type objects are useful in Python 2.2 and later because you can subclass them, as covered in Chapter 5. 13.3.2 The Code Object TypeAs well as by using built-in function compile, you can also get a code object via the func_code attribute of a function or method object. A code object's co_varnames attribute is the tuple of names of local variables, including the formal arguments; the co_argcount attribute is the number of arguments. Code objects are not callable, but you can rebind the func_code attribute of a compatible function object in order to wrap a code object into callable form. Module new supplies a function to create a code object, as well as other functions to create instances, classes, functions, methods, and modules. Such needs are both rare and advanced, and are not covered further in this book. 13.3.3 The frame TypeFunction _getframe in module sys returns a frame object from Python's call stack. A frame object has attributes that supply information about the code executing in the frame and the execution state. Modules traceback and inspect help you access and display information, particularly when an exception is being handled. Chapter 17 provides more information about frames and tracebacks. |