Showing posts with label workaround. Show all posts
Showing posts with label workaround. Show all posts

Tuesday, August 12, 2008

Python urlencode annoyance

O'Reilly has examples of how to urlencode a string for various languages. Every example has the same semantics -- a variable to define a string and a function to encode it -- except Python. Python's urlencode presumes you want to convert a dictionary whose key (which seems to be a name you should make up when you call this function) will be a GET variable that you would append to the tail of the URL. I think this presumes too much. I want to build a URL and simply encode the name of a file. I wish I could do this:
url = "http://foo.com/" + urlencode(file_name)
Instead I use a substring kludge since len("x=") is 2:
tmp = urlencode({'x':file_name})
url = "http://foo.com/" + tmp[2:]
Applying this back to O'Reilly's example:
from urllib import urlencode
artist = "Kruder & Dorfmeister"
tmp = urlencode({'x':artist})
artist = tmp[2:]
I guess Python is promoting a paradigm where URL values are arguments to methods and the syntax of a URL itself is abstracted away. But I still would have kept urlencode like the other languages and offered a variation of this function that does whatever Python is trying to promote.