|
| 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 | + # >>> Tobin is 20 years old |
| 23 | +
|
| 24 | + person = {'first':'Tobin', 'last': 'Brown', 'age':20} |
| 25 | + print('{0} {1} is {2} years old'.format(person['first'], person['last'], person['age'])) # bad |
| 26 | + # >>> Tobin Brown is 20 years old |
| 27 | +
|
| 28 | +
|
| 29 | +Best practice |
| 30 | +------------- |
| 31 | + |
| 32 | +By using the dictionary keys in the string we are formatting, the code is much more readable and explicit. |
| 33 | + |
| 34 | +.. code:: python |
| 35 | +
|
| 36 | + person = {'first':'Tobin', 'age':20} |
| 37 | + print('{first} is {age} years old'.format(**person)) |
| 38 | + # >>> Tobin is 20 years old |
| 39 | +
|
| 40 | + person = {'first':'Tobin', 'last': 'Brown', 'age':20} |
| 41 | + print('{first} {last} is {age} years old'.format(**person)) |
| 42 | + # >>> Tobin Brown is 20 years old |
| 43 | +
|
| 44 | +
|
| 45 | +Going even further, the same result can be achieved with your own objects by using ``obj.__dict__``. |
| 46 | + |
| 47 | +.. code:: python |
| 48 | +
|
| 49 | + class Person(object): |
| 50 | +
|
| 51 | + def __init__(self, first, last, age): |
| 52 | + self.first = first |
| 53 | + self.last = last |
| 54 | + self.age = age |
| 55 | +
|
| 56 | + def __str__(self): |
| 57 | + return '{first} {last} is {age} years old'.format(**self.__dict__) |
| 58 | +
|
| 59 | +
|
| 60 | + person = Person('Tobin', 'Brown', 20) |
| 61 | + print(person) |
| 62 | + # >>> Tobin Brown is 20 years old |
0 commit comments