Skip to content

Instantly share code, notes, and snippets.

@onemach
Created April 5, 2012 14:30
Show Gist options
  • Save onemach/2311470 to your computer and use it in GitHub Desktop.
Save onemach/2311470 to your computer and use it in GitHub Desktop.
JavaScript-like object in python
class D(dict):
def __init__(self):
dict.__init__(self)
def __getitem__(self, key):
val = D()
try:
val = dict.__getitem__(self, key)
except:
dict.__setitem__(self, key, val)
return val
def __setitem__(self, key, val):
dict.__setitem__(self, key, val)
#I like JavaScript object. So I did this.
#try this
#> a = D()
#> a[1][2][3] = 4
@fajran
Copy link

fajran commented Apr 5, 2012

Isn't line 6 supposed to be val = D()?

@onemach
Copy link
Author

onemach commented Apr 5, 2012

@fajran yeah... I changed the name and forgot that. edited, thx

@fulmicoton
Copy link

Have you tried using defaultdict?

from collections import defaultdict
D=lambda : defaultdict(D)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment