Skip to content
David Liu edited this page Jan 12, 2026 · 27 revisions
  • 末尾加逗号会把表达式变成元组
    • x = [1, 2, 3],  # x 是一个 tuple,里面有一个 list
      
  • naming-conventions
  • os.environ vs os.getenv
    • os.environ['key'] raises an exception if the environmental variable key does not exist
    • os.getenv('key') does not raise an exception, but returns None
    • os.getenv is a wrapper to os.environ.get
  • is vs ==
    • is: 指针相同
    • ==:值相同,常用于值和常量比较
  • spread operator in python:
    • for dict: **
    • for tuple: *
  • 列表推导式 List Comprehensions
    • 型如numbers = [x for x in range(10)]

类class

  • Python import 并非只是把一个文本插入另一个文本而已。程序在第一次导入指定文件时,会执行如下steps:
    1. 找到模块文件
    2. 如果模块module位于包package中,执行包初始化,即运行__init__.py。这使得__init__.py更适合作为common.py
    3. compile into bytecode
    4. 执行模块的代码。在这之后,导入相同模块时,会跳过这些steps,而只提取内存中已加载的模块对象。已加载的模块存储在sys.modules表对象中。
  • getter and setter

类型Type

函数

大致而言,lambda就是没有预定义的函数

Best practice

  • Don't use enum, use string
  • Use dict than switch/case
  • quote ' or double-quote "
    • PEP 8 的建议非常简单:选一种风格,坚持用到底。

选一种风格,坚持用到底。

context manager

  • with 语句用于异常处理,封装了 try…except…finally 编码范式,提高了易用性。
    • with 语句实现原理建立在上下文管理器之上。
    • 上下文管理器是一个实现 __enter____exit__ 方法的类。
    • with 语句的对象类必须是一个上下文管理器的实现
  • contextlib里面提供了各种封装器,能将对象转化为context manager

pylint

  • Auto formatter: autopep8
  • basic syntax check: python -m compileall -q .

logging

请注意,根记录器的默认级别为 WARNING

Latest compiled version

  • 3.13.11
  • 3.12.12
  • 3.11.14
  • 3.10.19
  • 3.9.25

Clone this wiki locally