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
Active
Viewed 123 times
3

Bharath M Shetty
- 30,075
- 6
- 57
- 108
-
1`del dict` should work? – ayhan Sep 17 '17 at 12:11
-
Yep... this is a dupe (since you asked). – cs95 Sep 17 '17 at 12:11
-
@cᴏʟᴅsᴘᴇᴇᴅ you are really good at finding duplicates. :-) – Bharath M Shetty Sep 17 '17 at 12:16
-
That does not mean it isn't a good question. Some duplicates should be asked to allow users to find the same target through different search term. – cs95 Sep 17 '17 at 12:17
-
1@Bharathshetty slight aside, are you aware of [this](https://sopython.com/canon/) which can help. This dupe isn't in the list, but it can be handy. – roganjosh Sep 17 '17 at 12:58
2 Answers
3
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.

Willem Van Onsem
- 443,496
- 30
- 428
- 555
-
Yes I will never do that. It was bugging me from a long time so I asked it. – Bharath M Shetty Sep 17 '17 at 12:13
2
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()
print(d)
from contextlib import contextmanager
@contextmanager
def get_dict_back():
import builtins
yield builtins.dict
with get_dict_back() as build_dict:
d = build_dict({'a': 1})
print(d)
print(dict())
The buildin dict is only avaiable in the with-statement.
Output:
damn it, I override the buildins
{'a': 1}
damn it, I override the buildins

Menglong Li
- 2,177
- 14
- 19
-
1It seems counter intuitive to do this, because there's already an existing variable called "dict" you don't want to shadow that as well. Keeping it within it's namespace would be better. – cs95 Sep 17 '17 at 12:12
-
-
-
@Bharathshetty No kidding, in my post, I provide both ways and claims the side-effect. – Menglong Li Sep 17 '17 at 12:21