zermy
zermy

Reputation: 621

Is it safe to call dict.__init__ on already populated dictionary?

I have a class that inherits from the built in dict class. It used to look a bit like:

class AwesomeDictionary(dict):
    def __init__(self, *args, **args):
        self['hello'] = 'world'
        i = {}
        dict.__init__(i, *args, **kargs)
        self.update(i)

I implemented it like that with a temporary dictionary because I thought __init__ would create a brand new dictionary or at least clear it.

I only recently realized that you can do something like this in the Python interpreter with no problems:

f = {'hi':56, '67':89}
dict.__init__(f, **{'h':67})
print f
#You get:  {'67': 89, 'h': 67, 'hi': 56}

and if you specify the same field:

f = {'hi':56, '67':89}
dict.__init__(f, **{'hi':34})
print f
#You get:  {'67': 89, 'hi': 34}

So, in that case, it would appear that __init__ is acting the same as .update.

Is there a particular reason why this is the case and can I expect this to be consistent across implementations and versions?

On a similar note, is there any purpose for calling .update on a regular dictionary other than perhaps code cleainliness and readability (which is a perfectly fine reason mind you, I was just wondering if that is the only reason)?

Oh and I know I could just leave it as is and do an update for peace of mind, but it feels quite inefficient if you are doing the same thing twice.

I apologize if this is a silly question.

Thanks for your time.

Upvotes: 0

Views: 216

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124818

You can also call f.__init__(hi=34).

The __init__ method on objects is the initializer. It is called to initialize a newly created object, and usually the method assumes that the object is still fresh and empty when __init__ is executed.

If you call it again at a later time, if it'll work depends on the class. For dict it apparently works. I would not count on this working across versions, the behaviour of the dict.__init__ method you observed is not specified in the documentation. It just so happens that in CPython, __init__ is implemented as a self.update() (albeit in C).

The biggest drawback is that it will confuse anyone trying to understand your code. Why call __init__ when .update() is so much clearer?

Upvotes: 3

Related Questions