dict literals vs dict(**kwds)
bruno at modulix
onurb at xiludom.gro
Wed May 24 04:20:36 EDT 2006
George Sakkis wrote:
> Bruno Desthuilliers wrote:
>
>
>>George Sakkis a écrit :
>>
>>>Although I consider dict(**kwds) as one of the few unfortunate design
>>>choices in python since it prevents the future addition of useful
>>>keyword arguments (e.g a default value or an orderby function), I've
>>>been finding myself lately using it sometimes instead of dict literals,
>>>for no particular reason. Is there any coding style consensus on when
>>>should dict literals be preferred over dict(**kwds) and vice versa ?
>>
>>using dict literals means that you'll always have a builtin dict - you
>>cannot dynamically select another dict-like class. OTHO, you can only
>>use valid python identifiers as keys with dict(**kw).
>
>
> This is all good but doesn't answer my original question:
I thought it did - at least partly.
> under which
> circumstances (if any) would {'name':'Mike, 'age':23} be preferred
> over dict(name='Mike', age=23)
When you're sure you want a builtin dict (not any other dictlike) and/or
some keys are invalid Python identifiers.
> and vice versa,
When all your keys are valid Python identifiers, and you may want to use
another dict-like instead of the builtin dict. It's easy to replace the
dict() factory in a function, class, or whole module :
class MyDict(...):
# dict-like class
dict = MyDict
then all following calls to dict(**kw) in this namespace will use MyDict
instead of the builtin's one. Can't do that with dict litterals.
> or if it's just a matter
> of taste,
Partly also, but...
> similar to using single vs double quote for string literals
> (when both are valid of course).
Nope, this is not so similar, cf above.
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"
More information about the Python-list
mailing list