if x is not None, if not x is None중 어느 걸 써야 하나요?
조회수 15974회
저는 if not x is None
이 더 읽기 좋은 표현이라고 생각했는데
Google style guide에는 if x is not None
라고 쓰라고 돼 있습니다.
둘이 무슨 속도차이 같은게 있어서 그런 건가요?
아니면 if not x is None
이 가독성이 더 떨어져서 그런 건가요?
1 답변
-
코드를 쓸 때
not x is y
대신if x is not None
을 권장하는 이유는, 컴파일러에서는 뭘 쓰던 동일하게not (x is y)
로 처리 하지만 사람이 읽기에는(not x) is y
로 해석될 여지가 있기 때문입니다.다음에 보이는 것 처럼 둘은 같은 bytecode로 컴파일되기 때문에 수행 속도차는 없습니다.
Python 2.6.2 >>> import dis >>> def f(x): ... return x is not None ... >>> dis.dis(f) 2 0 LOAD_FAST 0 (x) 3 LOAD_CONST 0 (None) 6 COMPARE_OP 9 (is not) 9 RETURN_VALUE >>> def g(x): ... return not x is None ... >>> dis.dis(g) 2 0 LOAD_FAST 0 (x) 3 LOAD_CONST 0 (None) 6 COMPARE_OP 9 (is not) 9 RETURN_VALUE
댓글 입력