How to reassign dict functionality back to the 'dict'?


I accidentally assigned a dictionary to the keyword dict, now its leading to dict object not callable. So how can I reassign back the functionality without restarting the kernel?

Asked By: Bharath



It’s a bad idea to override the key words in Python.

If you want you dict back, use this:

from builtins import dict
d = dict()

But this codes will override your defined dict again. So you can use the following codes to control the scope:

dict = lambda: 'damn it, I override the buildins'

d = dict()

from contextlib import contextmanager

def get_dict_back():
    import builtins
    yield builtins.dict

with get_dict_back() as build_dict:
    d = build_dict({'a': 1})


The buildin dict is only avaiable in the with-statement.


damn it, I override the buildins
{'a': 1}
damn it, I override the buildins
Answered By: Menglong Li

dict is a builtin. Builtins are grouped together in the builtin package. So you can use:

import builtins
dict = builtins.dict

A piece of advice is to never override builtins: do not assign to variables named list, dict, set, int, float, etc.

That being said, you can remove dict from the scope as well. In that case Python will fallback on the builtins. So you delete the variable:

temp_dict = dict
del dict  # remove the `dict`, now it will delegate to the `dict` builtin

For example:

>>> dict = {}
>>> dict
>>> del dict
>>> dict
<class 'dict'>

So you delete it out of the scope, and then Python will again bind it to the “outer” scope.

Answered By: Willem Van Onsem
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.