Paul Rubin wrote:
Peter Hansen <pe***@engcorp.com> writes: Maybe it's nothing more than this distinction: dict() is a call which
*returns* an empty dictionary. {} *is* an empty dictionary.
I don't understand in what ways these are really distinct.
a = []
for i in range(2):
a.append({})
print (a[0] is a[1])
prints 0, if that helps. Clearly "a = {}" and "a = dict()" both run
some code that creates a new empty dictionary. It's not the case that
"a = {}" sets a to an empty dict created at compile time or anything
like that.
I agree. In that example, either is equally readable.
I think the example I would have in mind is a comparison:
if a == []:
# do something
if b != {}:
a.append(b)
or whatever.
I think the difference lies in ones intent. If the empty item is
going to be kept around and used, then a constructor approach seems
appropriate, maybe even arguably more readable. If the empty item
is merely a temporary, to be used and discarded, then the apparent
extra overhead of the call, and the less succinct syntax, lead me to
think the short form is preferable.
-Peter