Python
if x is not None
hayif not x is None
?
TLDR: Trình biên dịch Bytecode phân tích cả hai đến x is not None
- vì vậy để có thể đọc được, hãy sử dụng if x is not None
.
Khả năng đọc
Chúng tôi sử dụng Python vì chúng tôi coi trọng những thứ như khả năng đọc của con người, khả năng sử dụng và tính đúng đắn của các mô hình khác nhau của lập trình về hiệu suất.
Python tối ưu hóa cho khả năng đọc, đặc biệt là trong bối cảnh này.
Phân tích cú pháp và biên dịch mã byte
not
liên kết yếu hơn is
, do đó không có sự khác biệt logic ở đây. Xem tài liệu:
Các toán tử
is
và0 Kiểm tra nhận dạng đối tượng:>>> import ast >>> ast.dump[ast.parse['x is not None'].body[0].value] "Compare[left=Name[id='x', ctx=Load[]], ops=[IsNot[]], comparators=[Name[id='None', ctx=Load[]]]]" >>> ast.dump[ast.parse['not x is None'].body[0].value] "UnaryOp[op=Not[], operand=Compare[left=Name[id='x', ctx=Load[]], ops=[Is[]], comparators=[Name[id='None', ctx=Load[]]]]]"
1 là đúng khi và chỉ khi X và Y là cùng một đối tượng.>>> import ast >>> ast.dump[ast.parse['x is not None'].body[0].value] "Compare[left=Name[id='x', ctx=Load[]], ops=[IsNot[]], comparators=[Name[id='None', ctx=Load[]]]]" >>> ast.dump[ast.parse['not x is None'].body[0].value] "UnaryOp[op=Not[], operand=Compare[left=Name[id='x', ctx=Load[]], ops=[Is[]], comparators=[Name[id='None', ctx=Load[]]]]]"
2 mang lại giá trị sự thật nghịch đảo.>>> import ast >>> ast.dump[ast.parse['x is not None'].body[0].value] "Compare[left=Name[id='x', ctx=Load[]], ops=[IsNot[]], comparators=[Name[id='None', ctx=Load[]]]]" >>> ast.dump[ast.parse['not x is None'].body[0].value] "UnaryOp[op=Not[], operand=Compare[left=Name[id='x', ctx=Load[]], ops=[Is[]], comparators=[Name[id='None', ctx=Load[]]]]]"
>>> import ast
>>> ast.dump[ast.parse['x is not None'].body[0].value]
"Compare[left=Name[id='x', ctx=Load[]], ops=[IsNot[]], comparators=[Name[id='None', ctx=Load[]]]]"
>>> ast.dump[ast.parse['not x is None'].body[0].value]
"UnaryOp[op=Not[], operand=Compare[left=Name[id='x', ctx=Load[]], ops=[Is[]], comparators=[Name[id='None', ctx=Load[]]]]]"
0 được quy định cụ thể trong ngữ pháp Python như là một cải tiến dễ đọc cho ngôn ngữ:comp_op: ''|'=='|'>='|'