Pointers to the docs
>>> help(obj) >>> dir(obj)
List comprehensions and generators
numbers = [2, 3, 4, 5, 6, 7, 8, 9] [x * x for x in numbers if x % 2 == 0]
Generators might be thought of as lazy list comprehensions.
def generate_squares(): i = 1 while True: yield i*i i += 1
def main(): # do something here if __name__ == "__main__": main()
class Foo(object): 'Doc string for class' def __init__(self, a, b): 'Doc string for constructor' self.a = a self.b = b def square_plus_a(self, x): 'Doc string for a useless method' return x * x + a def __str__(self): return "Foo: a=%d, b=%d" % (self.a, self.b)
class Object(object): pass obj = MyEmptyClass() obj.foo = 123 obj.bar = "A super secret message dir(obj) ['__doc__', '__module__', 'bar', 'foo']
You can add methods, too, but they act a little funny. Self doesn't seem to work.
Reading text files line by line can be done like so:
with open(filename, 'r') as f: for line in f: dosomething(line)
try: raise Exception('My spammy exception!', 1234, 'zot') except Exception as e: print type(e) print e finally: print "cleanup in finally clause!"
Traceback prints stack traces.
import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
Finally added in Python 2.5:
x = true_value if condition else false_value
Packages, Libraries, Modules
What do they call them in Python? Here's a quick tip for finding out where installed packages are:
python -c 'import sys, pprint; pprint.pprint(sys.path)'
To find out what packages are installed, open a python shell and type:
Python's magic methods are the source of much confusion. Rafe Kettler's Guide to Python's Magic Methods sorts things out beautifully.