10.2. Introspection

One of the great strengths of a dynamic programming language, such as Python, is that it is possible to examine and even manipulate the program code at run-time. The idea of introspective programs may sound esoteric and mind-bending, but on examination it provides a clean way to solve some rather mundane tasks.

The core idea is simple: given that your program includes a function or an object named xyzzy, you can use the string "xyzzy" to access that object, rather than specifying the name in your source code. Thus, your program can choose an appropriate action to take based on a string originating from the network or from the user, without an if statement.

Introspection can be implemented in a straightforward manner using a symbol table that is maintained by the Python interpreter. The symbol table contains a mapping from all names defined in the program code to the corresponding objects. Actually, the symbol table can be thought of as a special dictionary that contains everything related to the internals of the current module. In some sense, it is like an internal address book for finding and executing code in a module.

At any point of execution, the interpreter maintains two separate symbol tables: one for the global scope and one for the local objects in the current function. Actually, the global keyword, which was first mentioned in Chapter 3, just instructs the interpreter to place an object in the global symbol table instead of the default local one. ...

Get Mobile Python: Rapid Prototyping of Applications on the Mobile Platform now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.