본문으로 바로가기
반응형

Not using dict keys when formatting strings

딕셔너리의 값을 문자열로 사용할 때, 명시적으로 모든 값들을 적어줄 필요가 없다.

예를 들어 아래와 같은 딕셔너리가 존재한다고 가정한다.

person = {
    'first': 'Tobin',
    'age': 20
}


Anti-pattern

person = {
    'first': 'Tobin',
    'age':20
}

print('{0} is {1} years old'.format(
    person['first'],
    person['age'])
)
# Output: Tobin is 20 years old

person = {
    'first': 'Tobin',
    'last': 'Brown',
    'age':20
}

# Bad: we have to change the replacement fields within
# our string, once we add new values
print('{0} {1} is {2} years old'.format(
    person['first'],
    person['last'],
    person['age'])
)  # bad
# Output: Tobin Brown is 20 years old

위 예제는 모든 문자열 포맷팅에 대해 직접 명시해주는 형태이다.

이런 형태는 좋지 않은 형태이다. 만약 우리가 다른 key-value쌍을 person딕셔너리에 추가한다면,

그에 대한 포맷쪽도 수정해줘야 하기 때문이다.


Best practice

person = {
    'first': 'Tobin',
    'age':20
}

print('{first} is {age} years old'.format(**person))
# Output: Tobin is 20 years old

person = {
    'first':'Tobin',
    'last': 'Brown',
    'age':20
}
print('{first} {last} is {age} years old'.format(**person))
# Output: Tobin Brown is 20 years old

따라서 위처럼 수정해주는 편이 좋다. (읽기에도 좋고)

class Person(object):

    def __init__(self, first, last, age):
        self.first = first
        self.last = last
        self.age = age

    def __str__(self):
        return '{first} {last} is {age} years old'.format(**self.__dict__)


person = Person('Tobin', 'Brown', 20)
print(person)
# Output: Tobin Brown is 20 years old

좀 더 수정해보자면, 위와 같은 형태로도 작성할 수 있다.

obj.__dict__를 사용하여 동일한 결과를 얻을 수 있다.


출처 : https://docs.quantifiedcode.com/python-anti-patterns/readability/not_using_dict_keys_when_formatting_strings.html

반응형