Skip to content

Commit 05020d9

Browse files
committed
added dict keys antipattern
1 parent 7d92d96 commit 05020d9

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
2+
Not using dict keys when formatting strings
3+
===========================================
4+
5+
When formatting a string with values from a dictionary, you can use the dictionary keys instead of explicity defining all of the format parameters. Consider this dictionary that stores the name and age of a person.
6+
7+
8+
.. code:: python
9+
10+
person = {'first':'Tobin', 'age':20}
11+
12+
13+
Anti-pattern
14+
------------
15+
16+
Here is an example of formatting the string with values from the person. This is bad! If we added another key-value pair to the person dictionary, we would have to change the string and the format arguments
17+
18+
.. code:: python
19+
20+
person = {'first':'Tobin', 'age':20}
21+
print('{0} is {1} years old'.format(person['first'], person['age'])) # bad
22+
23+
person = {'first':'Tobin', 'last': 'Brown', 'age':20}
24+
print('{0} {1} is {2} years old'.format(person['first'], person['last'], person['age'])) # bad
25+
26+
27+
Best practice
28+
-------------
29+
30+
By using the dictionary keys in the string we are formatting, the code is much more readable and explicit.
31+
32+
.. code:: python
33+
34+
person = {'first':'Tobin', 'age':20}
35+
print('{first} is {age} years old'.format(**person))
36+
37+
person = {'first':'Tobin', 'last': 'Brown', 'age':20}
38+
print('{first} {last} is {age} years old'.format(**person))
39+
40+
41+
Going even further, the same result can be achieved with your own objects by using ``obj.__dict__``.
42+
43+
.. code:: python
44+
45+
class Person(object):
46+
47+
def __init__(self, first, last, age):
48+
self.first = first
49+
self.last = last
50+
self.age = age
51+
52+
def __str__(self):
53+
return '{first} {last} is {age} years old'.format(**self.__dict__)
54+
55+
56+
person = Person('Tobin', 'Brown', 20)
57+
print(person)

0 commit comments

Comments
 (0)