每个程序员都应该知道的 Python 最佳实践

360影视 国产动漫 2025-05-19 15:10 2

摘要:def process_files(file1, file2, file3): with open(file1, 'r') as f1: with open(file2, 'r') as f2: with open(file3, 'r') as f3: pas

嵌套的 with 语句可能会变得混乱。使用 ExitStack 来保持整洁。

不好:

def process_files(file1, file2, file3): with open(file1, 'r') as f1: with open(file2, 'r') as f2: with open(file3, 'r') as f3: pass

好:

from contextlib import ExitStackdef process_files(file1, file2, file3): with ExitStack as stack: f1 = stack.enter_context(open(file1, 'r')) f2 = stack.enter_context(open(file2, 'r')) f3 = stack.enter_context(open(file3, 'r')) pass

不好:

def myfunction(num): MyVar = num / 3.5 return MyVar

好:

def my_function(num): my_var = num / 3.5 return my_va

不要直接将 API 密钥或密码存储在代码中!

坏:

password = "iLOVEcats356@33"

好:

import ospassword = os.getenv("MY_SECRET_PASSWORD")

不好:

data = {"name": "Alice", "age": 30}city = data["city"] if "city" in data else "Unknown"

好:

city = data.get("city", "Unknown")

不好:

def describe_type(obj): if isinstance(obj, str): return "It's a string" elif isinstance(obj, int): return "It's an integer" elif isinstance(obj, list): return "It's a list" else: return "It's something else"

好:

def describe_type(obj): match obj: case str: return "It's a string" case int: return "It's an integer" case list: return "It's a list" case _: return "It's something else"

来源:自由坦荡的湖泊AI一点号

相关推荐