background preloader

Python Tips, Tricks, and Hacks

Python's Mutable Default Problem Posted by tottinger on 05/23/2008 Today I was perusing a very fine python article all professional python programmers should read. I had to grin when I saw one of my favorite python quirks/flaws. def function(item, stuff = []): stuff.append(item) print stuff function(1) # prints '[1]' function(2) # prints '[1,2]' !!! The grin on my face was because I was bit by this one again last Tuesday. Saifoo.net: def function(item, stuff=None): if stuff is None: stuff = [] stuff.append(item) print stuff This, of course, gives the correct behavior because it creates a new empty list each time it is called without a second parameter. My solution actually combines some advice contained earlier in the article with the solution given for this problem: Mine def function(item, stuff=None): stuff = stuff or [] stuff.append(item) print stuff It’s not necessarily prettier, and I struggle with whether it is more obvious (to a Python programmer) or not.

Python: Myths about Indentation There are quite some prejudices and myths about Python's indentation rules among people who don't really know Python. I'll try to address a few of these concerns on this page. "Whitespace is significant in Python source code." No, not in general. Only the indentation level of your statements is significant (i.e. the whitespace at the very left of your statements). Everywhere else, whitespace is not significant and can be used as you like, just like in any other language. Also, the exact amount of indentation doesn't matter at all, but only the relative indentation of nested blocks (relative to each other). Furthermore, the indentation level is ignored when you use explicit or implicit continuation lines. Of course, most of the time you will want to write the blocks in separate lines (like the first version above), but sometimes you have a bunch of similar "if" statements which can be conveniently written on one line each. Have you ever seen code like this in C or C++?

Working with the Operating System Working with the Operating System In this topic we will look at the role of the Operating System (OS) and how we can access the OS from Python. So What is the Operating System? Most computer users know that their computer has an operating system, whether it be Windows, Linux or MacOS or some other variety. But not so many know exactly what the operating system does. This is compounded by the fact that most commercial operating systems come bundled with lots of extra programs that are not really part of the operating system per se, but without which the computer would not be very usable. The layer cake principle The answer lies in the way computers are built. The next layer up is the Basic Input Output System or BIOS. The next layer up from the BIOS is where we hit the operating system proper. As an example consider what happens when we open and read a file in Python: The final layer in the cake is the shell which is the user environment. Process Control User Access and Security Finding files

Another Do-It-Yourself Framework Introduction and Audience It’s been over two years since I wrote the first version of this tutorial. I decided to give it another run with some of the tools that have come about since then (particularly WebOb). Sometimes Python is accused of having too many web frameworks. And it’s true, there are a lot. This tutorial shows you how to create a web framework of your own, using WSGI and WebOb. For the longer sections I will try to explain any tricky parts on a line-by line basis following the example. What Is WSGI? At its simplest WSGI is an interface between web servers and web applications. WSGI more specifically is made up of an application and a server. A very simple application looks like this: >>> def application(environ, start_response):... start_response('200 OK', [('Content-Type', 'text/html')])... return ['Hello World!'] The environ argument is a dictionary with values like the environment in a CGI request. About WebOb WebOb is a library to create a request and response object.

Python for JavaScript Programmers By Atul Varma I couldn't find anything on the web that attempted to teach Python to readers who already knew JavaScript, so I thought I'd give it a shot, since a number of my friends at Mozilla don't know much about Python but know JavaScript incredibly well. The languages actually aren't that dissimilar--in fact, some of JavaScript's latest features have been borrowed directly from Python. Many thanks to those who have commented in my blog post about this tutorial; this rendition of it contains a number of changes as a result of that feedback. This is a good time to explain a bit about Python's design philosophy; hopefully it will give you a better idea of whether this is a language you'd like to use. While not syntactically enforced by many languages, whitespace is semantically meaningful during the reading and writing of code. if (someVar == 1) doSomething(); if (someVar == 1) doSomething(); doSomethingElse(); if (someVar == 1) { doSomething(); doSomethingElse(); } >>> import sha Unicode

Solving the Monty Hall problem with simulation in Python On at least two occasions I've met the Monty Hall problem. The first time it was in the book "The Curious Incident of the Dog in the Night-time" from Mark Haddon. And today I found it in an article called "Monty Hall strikes again - reveals fatal flaw in some of the most famous psychology experiments" It is so counter intuitive that it is amazing. The problem is this: Suppose you're on a game show, and you're given the choice of three doors: Behind one door is a car; behind the others, goats. My intuition says there is no need to change doors. from __future__ import divisionfrom random import shuffle, choice def get_random_doors(): doors = ["goat","goat","car"] shuffle(doors) return doors def get_host_open(doors, guest_pick1): host_open = 0 remaining_doors = [ k for k in [0,1,2] if k ! if doors[guest_pick_final] == "car": cars_won += 1 print strategy, cars_won/N simulation("stay")simulation("change") This is a Python 2.4 and 2.5 code.

On Monkey Patching Earlier this month I spoke at the International Computer Science Festival in Krakow. Krakow is a beautiful city with several universities, and it is becoming a high tech center, with branches of companies like IBM and Google. The CS festival draws well over a thousand participants; the whole thing is organized by students. While much of the program was in Polish, there were quite a few talks in English. Among these was Chad Fowler’s talk on Ruby. Chad is a very good speaker, who did an excellent job of conveying the sense of working in a dynamic language like Ruby. One of the points that came up was the custom, prevalent in Ruby and in Smalltalk, of extending existing classes with new methods in the service of some other application or library. As an example, I’ll use my parser combinator library, which I’ve described in previous posts. if:: tokenFromSymbol: #if.then:: tokenFromSymbol: #then.ifStat:: if, expression, then, statement. ifStat:: #if, expression, #then, statement.

Using Python to create UNIX command line tools A Python command line interface manifesto Noah GiftPublished on March 18, 2008 Can you write a command line tool? Maybe you can, but can you write a really good command line tool? This articles covers making a robust command line tool in Python, complete with built-in help menus, error handling, and option handling. For some strange reason, it is not widely known that the standard library in Python® has all of the tools necessary to make incredible powerful *NIX command line tools. Arguably, Python is the best language for making *NIX command line tools, period, due to its batteries-included philosophy, and its emphasis on readable code. Setup The optparse module in the Python Standard Library does most of the dirty work of creating a command line tool. Creating a Hello World command line tool The first step to writing a great command line tool is to define the problem you wish to solve. Let's get started by creating a Hello World command line tool. Hello World command line interface (CLI)

Ruby, Python, "Power" There are different opinions on the relative power of Ruby and Python. I'm not much more authoritative than other resources (though I'm not less authoritative either; most comparisons between the two languages are flawed). Ultimately I don't believe there are many (any?) places where one language is more "powerful" than the other (and not just in the "they are both Turing complete" sense). This was originally written August 2005. Ruby blocks usually the first topic when judging the two languages. This is trully annoying for the Twisted people, who have to write things in reverse because of it -- this is because Twisted (and asynchronous event-driven programming in general) does things like do_this(when_you_are_done_do=next_step), where the do_this function calls next_step() when it finishes. However, outside of asynchronous code -- which uses this callback style very heavily -- this is not a big problem in Python. def close_db_resources(): ... atexit.register(close_db_resources) Closures

Related: