Previous Page
Next Page

13.2. Internal Types

Some of the internal Python objects that I mention in this section are hard to use. Using such objects correctly and to the best effect requires some study of Python's own C (or Java, or C#) 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 many kinds of internal objects to your Python code, you can exert that control by coding in Python, even when a nodding acquaintance with C (or Java, or C#) is needed to read Python's sources in order to understand what is going on.

13.2.1. Type Objects

The built-in type named type acts as a factory object, returning objects that are types. Type objects don't have to support any special operations except equality comparison and representation as strings. However, 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, set, 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 as dict. Besides being callable to generate instances, many type objects are useful because you can subclass them, as covered in "Classes and Instances" on page 82.

13.2.2. The Code Object Type

As well as by using built-in function compile, you can get a code object via the func_code attribute of a function or method object. (For the attributes of code objects, see "Compile and Code Objects" on page 329.) Code objects are not callable, but you can rebind the func_code attribute of a function object with the correct number of parameters in order to wrap a code object into callable form. For example:

def g(x): print 'g', x code_object = g.func_code def f(x): pass f.func_code = code_object f(23)     # emits g 23

Code objects that have no parameters can also be used with statement exec or built-in function eval. Module new supplies a function to create code objects, as well as other functions to create old-style instances and classes, functions, methods, and modules. You can also create a new object by calling the type object you want to instantiate instead of calling a factory function from module new.

13.2.3. The frame Type

Function _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 18 provides more information about frames and tracebacks, and covers module inspect, which is generally the best way to perform such introspection.

Previous Page
Next Page