[python] PEP8 suggestions

HyunDong Lee·2022년 5월 16일
0

python

목록 보기
5/6
post-thumbnail

PEP style guide for python

bytes와 str의 차이점을 알고 사용하라

파이썬은 캐릭터를 2가지 방식으로 표현한다. bytes와 str, bytes는 raw data, unsigned 8-bit 값을 포함한다. encoding과정이 필요한지 필요하지 않은지를 판단하여 사용해야 함. bytes 내용은 decode를 거쳐야 한다.

  • str과 bytes 비교 불가, 같은 타입끼리 비교해야 함.
  • bytes는 8-bit 연속 값을 갖고, str은 unicode 연속값을 갖는다.
  • file을 열때는 'rb', 'wb'를 사용해라.
  • default가 text encoding이 포함되니 조심해야 한다. encoding된 값을 parameter로 넘겨라.
a = b'h\x65llo'
print(list(a))
print(a)

"""ouput"""
# []
# [104, 101, 108, 108, 111]
# b'hello'

C-style의 format string을 사용한다.

pantry = [
    ('avocados', 1.25),
    ('bananas', 2.5),
    ('cherries', 15),
]
for i, (item, count) in enumerate(pantry):
    print('#%d: %-10s = %.2f' % (i, item, count))
    
"""output"""
# #0: avocados = 1.25
# #1: bananas = 2.50
# #2: cherries = 15.00

zip을 통해 프로세스 반복을 병렬적으로 수행

names = ['a', 'bbbb', 'cc']
counts = [len(s) for s in names]

for name, l in zip(names, counts):
	print(name, l)
"""output"""
# a 1
# bbbb 4
# cc 2

zip을 이용하면 한 번의 반복으로 wrapping을 해준다. 여러개의 iterator를 병렬적으로 수행할 수 있게 해줌. 알고 있었지만 오랜만에 봐서 정리!

for loop 뒤에 else문을 피하라!

for x in []:
    print('Never runs')
else:
    print('For Else block!')

>>> 
For Else block!
for i in range(2, min(a, b) + 1):
    print('Testing', i)
    if a % i == 0 and b % i == 0:
        print('Not coprime')
break else:
    print('Coprime')
>>>
Testing 2
Testing 3
Testing 4
Coprime

def coprime(a, b):
    for i in range(2, min(a, b) + 1):
        if a % i == 0 and b % i == 0:
            return False
    return True
assert coprime(4, 9)
assert not coprime(3, 6)

0개의 댓글