Skip to content

Category Archives: Python

The __enter__ method in the with statement

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

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 log4j library for Java.
The problem is that there is no easy way to direct the logging to a new [...]

Using map with a dictionary in Python

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 [...]

Local SMTP in Python

From this Django change :
The easiest way to test your project’s use of e-mail is to use a “dumb” e-mail server that receives the e-mails locally and displays them to the terminal, but does not actually send anything. Python has a built-in way to accomplish this with a single command :
[...]