> For the complete documentation index, see [llms.txt](https://nining.website/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://nining.website/python/think/effective-python.md).

# Effective Python

本章节作为<\<Effective Python 编写高质量Python代码的59个有效方法>>读书笔记

## 用Pythonic方式来思考

### 第1条：确认自己所用的Python版本

```python
python --version

import sys
sys.version         # str
sys.version_info    # object
```

### 第2条：遵循 PEP 8 风格指南

PEP 8 针对Python代码格式而编订的风格指南，以便在阅读代码时可以根据这些名称看出它们在Python语言中的角色

* 函数、变量及属性应该用小写字母来拼写，各单词之间以下划线相连，如 lowercase\_underscore
* 受保护的实例属性，应该以单个下划线开头，如 \_leading\_underscore
* 私有的实例属性，应该以两个下划线开头，如 \_\_double\_leading\_underscore
* 类与异常，应该以每个单词首字母大写的形式来命名，如 CapitalizedWord
* 模块级别的常量，应该全部采用大写字母来拼写，各单词之间以下划线相连，如 ALL\_CAPS
* 类中的实例方法(instance method)，应该把首个参数命名为self，以表示该对象值
* 类方法(class method)的首个参数，应该命名为cls，以表示该类自身

文件中的那些 import 语句，总是应该使用绝对导入，可分为三部分

* 标准库
* 第三方模块
* 自用模块

### 第3条：了解 bytes、str 与 unicode 的区别

由于字符类型有区别，Python代码中经常会出现两种常见的使用情境

* 开发者需要原始8位字节值，通常以utf-8(或其他编码形式)来编码的字符
* 开发者需要操作没有特定编码形式的Unicode字符

```python
# coding:utf-8
import six
def to_unicode(s, encoding='utf-8', errors='strict'):
    if six.PY2:
        return s if isinstance(s, unicode)\
               else s.decode(encoding, errors=errors)
    else:
        return s if isinstance(s, six.string_types)\
               else s.decode(encoding, errors=errors)
​
def to_byte(s, encoding='utf-8', errors='strict'):
    if six.PY2:
        return s.encode(encoding, errors=errors)\
               if isinstance(s, unicode) else s
    else:
        return s.encode(encoding, errors=errors)\
               if isinstance(s, six.string_types) else s
```

### 第 4 条：用辅助函数来取代复杂的表达式

```python
from urllib.parse import parse_qs

my_values = parse_qs('red=5&blue=0&green=', keep_blank_values=True)
print(my_values)    # {'red': ['5'], 'blue': ['0'], 'green': ['']}

def get_first_int(values, key, default=0):
    found = values.get(key, [''])
    if found[0]:
        found = int(found[0])
    else:
        found = default
    return found

print(get_first_int(my_values, 'green'))
```

### 第 5 条：了解切割序列的办法

## 函数

### 第14条：尽量用异常来表示特殊情况，而不要返回None


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://nining.website/python/think/effective-python.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
