I have a container class for urls and their headers, Resource:
class Resource(object):
def __init__(self, url, headers):
self.url = url
self.content-length = headers['content-length']
self.content-type = headers['content-type']
# etc....
The headers argument to the __init__ method expects a dict returned from the getinfo() method of urllib2.urlopen(). I thought this would be a more readable way of packaging up the resource url and headers. Typing self.someheader = headers['someheader'] over and over made me wonder if there’s some way to automate creating variables from dictionary keys like this. Is this possible?
Python identifiers can’t have the
-symbol in them! So we can replace it with_in the keys.Changing the keys to lowercase makes them look like a conventional variable name, and, what is very important, removes uppercase/lowercase confusion (because headers are usually sent with capitalized keys).
If you’re using Python 2,
iteritemsis better here, as it doesn’t create a new list of items, but just lets you iterate over them, which Python 3 does by default.It may be a good idea to store those keys in a “private” dict (e. g.
self._headers). Then you can have much more control over the process with__getattr__and__setattr__, for example, an exception can be raised during an attempt to set an invalid key.