Sunday, September 25, 2011

Tips and tricks with Python ...

Sometimes when using new modules, we are confronted with the following problem.
The modules come with many features that are not fully documented.
Some of them we do not know.
We can use the dir function, but in most cases the result is a huge list.
Here is a simple detection method.
$ python
Python 2.7.1 (r271:86832, Apr 12 2011, 16:16:18)
[GCC 4.6.0 20110331 (Red Hat 4.6.0-2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import gnome
>>> dirlist=dir(gnome)

I put content above command in a list.
We need to processed now.
>>> dirlist.index('ui')
Traceback (most recent call last):
File "", line 1, in
ValueError: 'ui' is not in list
>>> dirlist.index('sound_play')

Here I found an item. To know something about it.
>>> help(dirlist[118])
no Python documentation found for 'sound_play'

Nothing about this. Let's use the command dir.
>>> dir(dirlist[118])
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Using the examples above, you can create a script to parse this source code and check if the functions are the same as our version.