Python Programming/Tips and Tricks
From Wikibooks, the open-content textbooks collection
There are many tips and tricks you can learn in Python:
- To stop a Python script on MS Windows from closing right after you launch one independently, add this code:
print 'Hit a key to exit' import msvcrt msvcrt.getch()
- You can also add this to do the same thing:
print 'Hit a key to exit' raw_input()
- Python already has a GUI interface built in: Tkinter
- Triple quotes are an easy way to define a string with both single and double quotes.
- String concatenation is expensive. Use percent formatting and string.join() for concatenation:
print "Spam" + " eggs" + " and" + " spam" # DON'T DO THIS print " ".join(["Spam","eggs","and","spam"]) # Much faster/more # common Python idiom print "%s %s %s %s" % ("Spam", "eggs", "and", "spam") # Also a pythonic way of # doing it - very fast
- cPickle is a fast, C written module for working with files.
import cPickle # You may want to import it as P for convenience.
- List comprehension are a very efficient way of perpetuating lists. Especially when creating one based on a file.
directory = os.listdir(os.getcwd()) # Gets a list of files in the # directory the program runs from filesInDir = [item for item in directory] # Normal For Loop rules apply, you # can add "if condition" to make a # more narrow search.
- Decorators can be used for handling common concerns like logging, db access, etc.
- While Python has no built-in function to flatten a list you can use a recursive function to do the job quickly.
def flatten(seq, a = []): """flatten(seq, a = []) -> list Return a flat version of the iterator `seq` appended to `a` """ if hasattr(seq, "__iter__"): # Can `seq` be iterated over? for item in seq: # If so then iterate over `seq` flatten(item, a) # and make the same check on each item. else: # If seq isn't an iterator then a.append(seq) # append it to the new list. return a
Not complete. Add more, please.

