Thursday, January 20, 2011

Python introspection

This is a handy article on python introspection. The article is old (Dec 2002) and uses Python 2.2 but you can work through the article with the current Python version which is 2.7. There are a few differences, for eg. two new keywords "as" and "with" will be displayed in the exercise which lists keywords, but most of the exercises are useful to get an understanding of Python's introspection abilities.

http://www.ibm.com/developerworks/library/l-pyint.html

One thing to note: in listing 29 (Types), its worth mentioning that if you use the 'type' function on modules , it only works for modules that are loaded. For modules that are not, you get an error. Calling type on built-ins will not give an error since built-ins like int are always loaded on initialization. Here's an example:


Python 2.6.3 (r263rc1:75186, Oct 2 2009, 20:40:30) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> type(int)
< type 'type' >
>>> type(sys)
Traceback (most recent call last):
File "", line 1, in
NameError: name 'sys' is not defined
>>> import sys
>>> type(sys)
< type 'module' >
>>>

No comments:

Post a Comment