Python has some neat features you don’t need every day but are still occasionally useful.
- Nested functions (closures):
Example:
- def a(b):
- def c(d):
- return b+d
- return c
A will return a function that adds B to it’s argument. Very useful to pass to functions like map() or filter().
2. Decorators
Example:
- def decorator(f):
- def b(*args):
- print ("calling "+f.__name__)
- return f()
- return b
- @decorator
- def func(a, b):
- return a*b
The decorator means that the func=decorator(func). In this case, decorator is a closure that prints “calling func” before every call to func. You could, for example, have a profiling decorator that measures the time between the start and end of your function. There are also built in decorators like the attribute function to make something like a C# get {}.
3. Iterator comprehension:
- (i**2 for i in range(2, 24, 2) if str(i)[0]!='1')
Very usefull features. You can replace complicated loops and lists with neat, compact statements, and it’s also much faster than loops or list comprehension because the values are not stored but rather calculated when you need them. If you break out of a loop using a iterator, the rest of the iterator will not be stored or calculated.
4. __name__
- class MyProgram(object):
- def __init__(self):
- pass #you should only set variables,
- #not anything error prone here
- def run(self):
- pass #main program logic
- def cleanup(self):
- pass #your cleanup code here
- if __name__=="__main__":
- try:
- prog=MyProgram()
- prog.run()
- finally:
- prog.cleanup()
The __name__==”__main__” makes the code not execute when the file is imported from another script. In this way, if you want to use some of the class code from another project, just import it. You won’t have to worry about side effects.
Putting logic in a class has many benefits even for small projects. Keeping local data strictly separate from global data means you have less variable names to worry about. You can easily make functions without having to worry about how data will be passed back and forth.
5. Lambda
- filter(lambda x: str(x)[0] in ('1','3'), range(0,99))
define a quick, inline function. Similar to the => in C#.
6. Looping over files
- file=open("checksums")
- checksums={i.split("\t")[0]: i.split("\t")[1] for i in file}
- f.close()
I just read a csv file into my dictionary in 3 lines, and it isn’t even unreadable. This is why I love python.
7. Tuples
- g=(1,2,2312,"blo")
A tuple is basically a immutable, yet much better version of a list. It’s much faster, saves a lot of memory, you can’t change it by accident, and it’s hash-able so it can be used as a dictionary key.
8. Useful builtin modules:
- import itertools #stuff like Cartesian product and permutation
- import functools #lots of decorators, for example a decorator that stores the last output in a cage and uses it again if possible
- import sys, os #do system level stuff
- import subprocess, multithreading, multiprocessing #various multithreading strategies
- import curses #mess with the terminal
- import tkinter #make fancy GUIs
- import pickle #serialize objects
- import urllib, ftplib, httplib, poplib #communicate with the internet
- import md5, zlib, gzip, csv, xml, json #common file formats
9. Useful third party modules:
- import twisted #asyncronious network programming
- import pygame #graphics programming
- import crypto #user friendly cryptography
- import httplib2 #more standards-compliant http
- import numpy #advanced math and statistics
- import django #python HTTP server framewor