Python is dynamic -- so you can redefine what 'dict' means in any of your scopes, while Python's syntax is absolutely nonprogrammable. Thus the Python parser can conclude, when it sees the curly braces, that it must build a dict. A dict(..)
expression must always be evaluated like any other function call; lookup the name, build argument tuple etc.
In effect, using container literals like the {}
curly braces is the closest you can come to static type declarations in Python.
I think this has influenced the Python 3 decision to introduce set literals like s = {1,2,3}
.
It does happen that programmers reassign python builtins! I think this is mostly by mistake, and mostly limited to local variables (and Python's namespaces make sure it can't do too much harm!) Here is a Google Code Search for code reassigning dict
. I think the strangest example is dict = dict()
; by that point, it should be obvious what you are doing!
That it's possible to do this doesn't mean you should do it. Yes, for example thinking that dict should really be called hash
in python and swapping out the other builtin called hash is not something you should do:
hash, checksum = dict, hash
:-)
An example of code that does this is found right in the Python standard library. That's right, here is from line 92 of shelve.py:
def __init__(self, dict, protocol=None, writeback=False):
self.dict = dict
if protocol is None:
protocol = 0
self._protocol = protocol
self.writeback = writeback
self.cache = {}
This is a very typical example; dict is used as a method argument, and no-one notices and it does no harm, since the method is very short. Use syntax highlighting for builtins to catch this, is my suggestion.