-1

I am quite an average programmer in python and i have not done very complex or any major application with python before ... I was reading new class styles and came across some very new things to me which i am understanding which is data types and classes unification

class defaultdict(dict):

    def __init__(self, default=None):
       dict.__init__(self)
       self.default = default

   def __getitem__(self, key):
       try:
           return dict.__getitem__(self, key)
       except KeyError:
           return self.default

but whats really getting me confused is why would they unify them? ... i really can't picture any reason making it of high importance .. i'll be glad if anybody can throw some light on this please Thank you

oluwalana
  • 21
  • 5

1 Answers1

2

The primary reason was to allow for built-in types to be subclassed in the same way user-created classes could be. Prior to new-style classes, to create a dict-like class, you needed to subclass from a specially designed UserDict class, or produce a custom class that provided the full dict protocol. Now, you can just do class MySpecialDict(dict): and override the methods you want to modify.

For the full rundown, see PEP 252 - Making Types Look More Like Classes

For an example, here's a dict subclass that logs modifications to it:

def log(msg):
    ...

class LoggingDict(dict):
    def __setitem__(self, key, value):
        super(LoggingDict, self).__setitem__(key, value)
        log('Updated: {}={}'.format(key, value))

Any instance of LoggingDict can be used wherever a regular dict is expected:

def add_value_to_dict(d, key, value):
    d[key] = value

logging_dict = LoggingDict()

add_value_to_dict(logging_dict, 'testkey', 'testvalue')

If you instead used a function instead of LoggingDict:

def log_value(d, key, value):
    log('Updated: {}={}'.format(key, value))

mydict = dict()

How would you pass mydict to add_value_to_dict and have it log the addition without having to make add_value_to_dict know about log_value?

Matthew Trevor
  • 14,354
  • 6
  • 37
  • 50
  • How helpful as it been to you sir? – oluwalana Mar 17 '14 at 01:58
  • You don't need to pass it to add_value_to_dict .. Having done mydict = dict() ... Then log_value(mydict, 'testkey', 'testvalue') – oluwalana Mar 17 '14 at 02:38
  • Sorry, `log_value` shouldn't have done the addition, as it's only a logger. Question still stands: how can I log additions made to a `dict` by a function with a separate function? – Matthew Trevor Mar 17 '14 at 02:39
  • why should the two functions not know each other? ... because you had answered it already in your code? – oluwalana Mar 17 '14 at 02:44
  • This isn't the place to get into the benefits of loose coupling. You asked for an answer and got it. If you don't need to use it, don't. Otherwise, you're descending into either pedantry or trolling. – Matthew Trevor Mar 17 '14 at 02:46