>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
파이썬의 선, 팀 피터
아름다운 코드는 지저분한 코드보다 낫다.
명확한 코드는 암시적인 코드보다 낫다.
단순한 코드가 복잡한 코드보다 낫다.
복잡한 코드가 난해한 코드보다 낫다.
단조로운 코드가 복잡한 코드보다 낫다.
읽기 쉬운 코드는 읽기 어려운 코드보다 낫다.
가독성은 중요하다.
규칙을 깰 정도로 특별한 경우란 없다.
하지만 실용성은 이상을 능가한다.
에러를 결코 조용히 넘어가지 않도록 한다.
명시적으로 조용히 넘어가라고 하더라도 조용히 넘어가지 않는다.
모호한 코드를 대면할 때마다 추측하고 싶은 유혹을 거절하라.
문제를 해결할 단 하나의 명확하고 바람직한 방법이 있을 것이다.
하지만 처음에 코딩을 할 때는 잘 모를 수 있기에 코드의 동작 방법을 정확히 알지 못 할 수 있다.
아무 것도 안하는 것보다 지금 하는 게 낫다.
하지만 아무 것도 하지 않는 것이 지금 *당장* 하는 것보다 나을 수도 있다.
설명하기 어려운 구현이라면 좋은 아이디어는 아니다.
쉽게 설명할 수 있는 구현이라면 좋은 아이디어일 것이다.
네임스페이스는 매우 훌륭한 아이디어다. 많이 사용하자
namespace란?
Python namespace에 대한 이해 / Python 네임스페이스
PEP = Python Enhancement Proposals
PEP 8 -- Style Guide for Python Code
PEP8 한글 번역
Luavis' Dev Story - Python PEP 8
→ 다른 줄과 구분되도록 하는 것이 핵심
magic(r=real, i=imag)
snake_case
표기법PascalCase
표기법_leading_underscore
< 밑줄 1개__leading_underscore
< 밑줄 2개MAX_OVERFLOW
와 TOTAL
if not a is b
→ if a is not b
/
으로 줄을 나누기 보단, 괄호 안에서 줄바꿈을 한다if not 컨테이너
를 활용하자seq = []
# good
if not seq:
if seq:
# bad
if len(seq):
if not len(seq):
# good
if foo == 'blah':
do_blah_thing()
do_one()
do_two()
do_three()
# ok
if foo == 'blah': do_blah_thing()
for x in lst: total += x
while t < 10: t = delay()
# bad
if foo == 'blah': do_blah_thing()
else: do_non_blah_thing()
try: something()
finally: cleanup()
do_one(); do_two(); do_three(long, argument,
list, like, this)
if foo == 'blah': one(); two(); three()
# bad
import mymodule
# good
import mypkg.mymodule
from mypkg.mymodule import *
from mypkg import mymodule
# 상대경로
from . import mymodule
from .mymodule import example
출처: https://codedragon.tistory.com/10309 [CodeDragon]
# 우선 순위가 낮은 연산자 주위에 공백을 주자
# bad
hypot2 = x * x + y * y
c = (a + b) * (a - b)
# good
hypot2 = x*x + y*y
c = (a+b) * (a-b)
# 예외를 처리할(catch)때에는 범용적인 except: 절 대신, 처리할 특정한 예외를 명시
try:
import platform_specific_module
except ImportError:
platform_specific_module = None
# try/except 절을 사용할 때에는 try 절이 적용되는 코드의 범위를 최소화
try:
value = collection[key]
except KeyError:
return key_not_found(key)
else:
return handle_value(value)
# string 모듈 대신 문자열 메서드를 사용한다
# 문자열 메서드는 항상 더 빠르며 유니코드 문자열과 동일한 API를 공유
if foo.startswith('bar'): # good
if foo[:3] == 'bar': # bad
# ==를 사용해서 True/False 값을 bool값과 비교하지 않는다
if greeting: # good
if greeting == True: # bad
if greeting is True: # worst
코드 자동 포메팅도 있다!
autopep8, black, yapf, etc