Python Notes: Difference between revisions

From Federal Burro of Information
Jump to navigationJump to search
No edit summary
No edit summary
Line 24: Line 24:




</pre>
== AutoVivification ==
<pre>
import pprint
class Vividict(dict):
    def __missing__(self, key):
        value = self[key] = type(self)()
        return value
d = Vividict()
d['foo']['bar']
d['foo']['baz']
d['fizz']['buzz']
d['primary']['secondary']['tertiary']['quaternary']
pprint.pprint(d)
</pre>
</pre>

Revision as of 04:22, 9 December 2016

Docs:

what's in that object?

https://download.tuxfamily.org/jeremyblog/diveintopython-5.4/py/apihelper.py

/apihelper.py

/apihelper.py - short

then use it like this:

#!/usr/bin/env python

from apihelper import info

mything

info(mything)


AutoVivification

import pprint

class Vividict(dict):
    def __missing__(self, key):
        value = self[key] = type(self)()
        return value

d = Vividict()

d['foo']['bar']
d['foo']['baz']
d['fizz']['buzz']
d['primary']['secondary']['tertiary']['quaternary']
pprint.pprint(d)