SmartDict - a smart 'dict' wrapper

14 July 2005   9 comments   Python

https://www.peterbe.com/plog/SmartDict/SmartDict.py

Mind That Age!

This blog post is 13 years old! Most likely, its content is outdated. Especially if it's technical.

For a work project we needed a convenient way to wrap our SQL recordset, instance objects and dictionary variables to share the same interface. The result is SmartDict which makes it possible to assert that access can be made in any which way you want; something that is very useful when you write templates and don't want to have to know if what you're working with is a dict or a recordset.

This doesn't work:

>>> d= {'name':"Peter"}
>>> print d.get('name') # fine
>>> print d.name # Error!!!

Likewise with some instance objects or record sets, this doesn't work:

>>> d = getRecordsetObject()
>>> print d.name # fine
>>> print d.get('name') # Error!!!

The solution is to process them all through our 'SmartDict':

>>> from SmartDict import SmartDict
>>>
>>> d= SmartDict({'name':"Peter"})
>>> print d.get('name') # fine
>>> print d.name # fine
>>>
>>> d = SmartDict(getRecordsetObject())
>>> print d.name # fine
>>> print d.get('name') # fine

The example above doesn't give much justice to SmartDict because if you know exactly which object you have to deal with you will make sure not to access it incorrectly. SmartDict is useful in cases of integration and development where any two systems are quite far apart and you might not just know what to expect. Feedback?

Comments

John P. Speno

Why use type() instead of isintance()?

Peter Bengtsson

what benefit does isinstance give over type()? I'm not arguing, I'm asking.

Personally I think:
if isinstance(obj, (tuple,list)):
is more confusing (especially for newcomers) than:
if type(obj) in (types.ListType, types.TupleType):

Chuck

isinstance will also return True if obj is a sublcass of tuble or list. It is usually considered safer to use isinstance unless you know for sure that the type will be a tuple or list and not a sublcass of those.

Peter Bengtsson

That is very useful to know! Thank you.

John P. Speno

In general, isinstance(foo, klass) returns True if
foo is an instance of klass or a subclass of it. It can also accept types.* instead of classes. Martelli calls it the lesser of two evils. :-)

Peter Bengtsson

It's just a of an oddity in python that 'list' is a type object and not a <type 'function'> like one'd expect it to be.

Gerhard Häring

Of course since Python 2.2, you could just write: type(obj) in (list, tuple) ;)

Peter Bengtsson

indeed.

Anonymous

another implementation, but allows more than one mapping in the creator, also less restrictive with what it can be updated from:

class SmartDict(dict):

....def __init__(self, *a, **kw):

........super(SmartDict, self).__init__(**kw)
........for x in a:
............try:
................self.update(x)
............except TypeError:
................self.update(x.__dict__)
........self.__dict__ = self

Your email will never ever be published


Related posts

Previous:
Rent a chest 12 July 2005
Next:
Kung Fu in Clapham with Richard 17 July 2005
Related by Keyword:
Items function in JavaScript for looping over dictionaries like Python 23 February 2018
Fastest way to uniquify a list in Python >=3.6 23 December 2017
Be careful with using dict() to create a copy 09 September 2015
When to __deepcopy__ classes in Python 14 March 2012
Pleonasm 11 June 2006
Related by Text:
jQuery and Highslide JS 08 January 2008
I'm back! Peterbe.com has been renewed 05 June 2005
Anti-McCain propaganda videos 12 August 2008
Ever wondered how much $87 Billion is? 04 November 2003
Guake, not Yakuake or Yeahconsole 23 January 2010