Lambda lambda lambda

It can help ya help ya help ya.

It’s Python’s lambda function1! Pesky urllib2 not allowing you to construct a DELETE request? Environment Overlords not letting you install a sane http module like Requests2? Don’t like what a module you have no control over is doing for you?

Lambda the damn thing!

For example urllib2 has a method called .get_method(). It returns the type of HTML request being made. In their infinite wisdom, the writers of urllib2 thought there were only two useful types of request anyone would ever want to make using their module, GET and PUT. The method looks at the URL and if it sees post data it returns “POST”. Otherwise it returns “GET”.

But it’s a modern Web we live in and we want to do modern things like make calls against a RESTful api provided by a vendor. Sometimes that vendor uses the kind of request being sent to determine the kind of action to take. Makes sense, no? But urllib2 spits on us and makes us write bad checks. What shall we do?

In this case we just hack the bejesus out of the .get_method() method and force it to return “DELETE” every time.


import urllib2
req = urllib2.Request( "http://www.example.com" )
req.get_method = lambda: "DELETE"

Now we can run DELETE requests against the RESTful API all damn day long. And then, later, when we want to do a “GET” all we have to do is lambda the damn thing again and make it return “GET”. Yay for us!

Yay for lambdas!

This is my rose for the day.

1http://www.secnetix.de/olli/Python/lambda_functions.hawk
2http://docs.python-requests.org/en/latest/

7 thoughts on “Lambda lambda lambda

Comments are closed.