A Newb Learns Python

Where is that Module?

Want to see the source on a Python module but can’t find the class, just use this nifty trick to figure out where the file is:

>>> import memcache
>>> memcache
<module 'memcache' from '/usr/local/lib/python2.6/dist-packages/python_memcached-1.47-py2.6.egg/memcache.pyc'>

You probably want the “.py” file as opposed to the “.pyc” but it will be in the same directory.

Easily Print Custom Python Objects

I can’t tell you how many times I’ve tried to print a python object only to get back the non-useful “<__main__.Foo instance at 0x1008eda28>”. Instead just call “vars” on the object.

>>> class Foo:
...     def __init__(self, a, b):
...             self.a = a
...             self.b = b
...             self.life = 42
... 
>>> f = Foo(1337, "meat")
>>> vars(f)
{'a': 1337, 'life': 42, 'b': 'meat'}

What methods can you call on a Python object?

I always forget method names. This handy dandy method tells you the names of the methods you can call on an object.

>>> dir({})
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
>>> class Foo:
...     def __init__(self):
...             pass
...     def magic(self):
...             pass
>>> 
>>> f = Foo()
>>> dir(f)
['__doc__', '__init__', '__module__', 'magic']
>>>