아래는 「파이썬 코딩의 기술 (Effective Python)」 2판에서 아이템 1, 2, 3을 책 예제 코드와 함께 정리한 내용입니다.
sys.version_info
를 사용하면 안전하다.import sys
print(sys.version_info) # 예: sys.version_info(major=3, minor=9, micro=1, ...)
print(sys.version) # 예: '3.9.1 (default, Dec 11 2020, 14:32:07)'
if sys.version_info >= (3, 9):
print("Python 3.9 이상의 기능을 사용할 수 있습니다.")
else:
print("구버전: 호환 코드 필요")
sys.version_info
는 튜플 형태 → (주버전, 부버전, 마이크로 버전, …)# ✅ 좋은 예 (PEP 8 준수)
def calculate_area(radius: float) -> float:
pi = 3.14159
return pi * (radius ** 2)
# ❌ 나쁜 예 (PEP 8 위반)
def CalculateArea( Radius ):
return 3.14159*(Radius**2)
str
→ 유니코드 문자열, bytes
→ 바이트 시퀀스.a = b'h\x65llo'
print(list(a)) # [104, 101, 108, 108, 111]
print(a) # b'hello'
a = 'a\u0300 propos'
print(list(a)) # ['a', '̀', ' ', 'p', 'r', 'o', 'p', 'o', 's']
print(a) # à propos
def to_str(bytes_or_str):
if isinstance(bytes_or_str, bytes):
value = bytes_or_str.decode('utf-8')
else:
value = bytes_or_str
return value # 항상 str 인스턴스 반환
def to_bytes(bytes_or_str):
if isinstance(bytes_or_str, str):
value = bytes_or_str.encode('utf-8')
else:
value = bytes_or_str
return value # 항상 bytes 인스턴스 반환
print(repr(to_str(b'foo'))) # 'foo'
print(repr(to_str('bar'))) # 'bar'
print(repr(to_str(b'\xed\x95\x9c'))) # '한'
print(repr(to_bytes(b'foo'))) # b'foo'
print(repr(to_bytes('bar'))) # b'bar'
print(repr(to_bytes('한글'))) # b'\xed\x95\x9c\xea\xb8\x80'
# b'one' + 'two' # TypeError
# 'one' + b'two' # TypeError
assert b'red' > b'blue'
assert 'red' > 'blue'
# assert 'red' > b'blue' # TypeError
print(b'foo' == 'foo') # False
print(b'red %s' % b'blue') # b'red blue'
print('red %s' % 'blue') # 'red blue'
# print(b'red %s' % 'blue') # TypeError
print('red %s' % b'blue') # 'red b\'blue\''
# 바이너리 쓰기
with open('data.bin', 'wb') as f:
f.write(b'\xf1\xf2\xf3\xf4\xf5')
# 바이너리 읽기
with open('data.bin', 'rb') as f:
data = f.read()
# 텍스트 읽기 (특정 인코딩 지정)
with open('data.bin', 'r', encoding='cp1252') as f:
data = f.read()
assert data == 'ñòóôõ'
str
↔ bytes
변환 시 반드시 encode
/ decode
사용
네트워크, 파일 IO, 바이너리 데이터 다룰 때 주의
비교, 연결, 포맷팅 시 타입 일관성을 유지해야 한다
파일 모드:
wb
/ rb
→ 바이트w
/ r
→ 텍스트(인코딩 필요)아이템 | 핵심 내용 |
---|---|
1. 파이썬 버전 관리 | sys.version_info 로 안전하게 버전 확인 및 조건부 코드 작성 |
2. PEP 8 스타일 | 협업과 유지보수를 위해 가이드 준수, 자동 포매터 사용 |
3. bytes vs str | 두 타입은 명확히 구분, 변환 시 encode /decode 필수, IO/포맷팅 시 주의 |