Created
October 24, 2011 04:18
-
-
Save andrewwatts/1308369 to your computer and use it in GitHub Desktop.
a dict that forces keys, which are likely camelCase, into under score keys.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class underscore_dict(dict): | |
""" | |
a dict like object that forces key to be pythonic and follow the underscore | |
convention. | |
eg:: | |
>>> d = underscore_dict(dict(myKey='my_value')) | |
>>> print d | |
'my_key': 'my_value'} | |
>>> d['my_key'] = 'my_value_2' | |
>>> print d | |
{'my_key': 'my_value_2'} | |
>>> d.update(myKey='my_value_3') | |
>>> print d | |
{'my_key': 'my_value_3'} | |
>>> del d['my_key'] | |
>>> print d | |
{} | |
And this is what happens when java code gets too close to python code. | |
""" | |
def __init__(self, *args, **kwargs): | |
self.update(*args, **kwargs) | |
def __setitem__(self, key, value): | |
# translate java's camelcase name convention to python's | |
# underscore convention from: | |
# http://github.com/mw44118/pyohio-metaclasses-talk/blob/master/listing1.py#21 | |
pythonic_key = '' | |
for c in key: | |
if c.isupper(): | |
pythonic_key += '_%c' % c.lower() | |
else: | |
pythonic_key += c | |
super(underscore_dict, self).__setitem__(pythonic_key, value) | |
def update(self, *args, **kwargs): | |
if args: | |
if len(args) > 1: | |
raise TypeError("update expected at most 1 arguments, got %d" % len(args)) | |
other = dict(args[0]) | |
for key in other: | |
self[key] = other[key] | |
for key in kwargs: | |
self[key] = kwargs[key] | |
def setdefault(self, key, value=None): | |
if key not in self: | |
self[key] = value | |
return self[key] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment