Tech and travel

Category: Tech

Stubbing out open() in Python

2012-05-15

Here’s an example that stubs out the open() function in Python using the mock library.

The __enter__ method in the with statement

2010-07-06

The with statement is a great addition to Python. One thing that might not be immediately clear from the documentation is how the __enter__ method has to be implemented. If you want to use the object containing __enter__ then you have to return self there. You should not create a new object and return it.

Python logging output file change

2009-08-12

I run unit tests in Python using the standard unittest module. The output should be logged to a file. For this Python has a standard logging library, which is somewhat similar to the logging library for Java. The problem is that there is no easy way to direct the logging to a new file for every test case. Here’s how I got around it. Firstly the setup method of my testcase object contains the following : def setUp(self): self.

Using map with a dictionary in Python

2009-07-21

When you have a dictionary in Python like this : mydict={'first':1, 'second':2, 'third':3} and you want to get the values into a list with a certain order you can do this : mylist=[mydict['first'], mydict['second'], mydict['third']] However, that can get a bit verbose if there are a lot of entries. For every entry you have to repeat ‘mydict’. An elegant way of solving this is using the map function : mylist=map(mydict.get,['first', 'second', 'third'])

Google App Engine

2008-04-14

Python‘s creator, Guido Van Rossum, has been hinting at this for a while, and it’s finally here : Google App Engine. It’s a way to build and host web apps on the Google servers. I put a small app together, which is a very simple variation on the ‘The Django Form Validation Framework on Google App Engine‘ article. It let’s you login, and store some data on workouts. On to some code : import cgi import wsgiref.

Copyright (c) 2024 Michel Hollands