markdown用python开发的“最佳实践最佳”(bobp)指南。(代码片段)

author author     2022-12-14     227

关键词:

# The Best of the Best Practices (BOBP) Guide for Python

A "Best of the Best Practices" (BOBP) guide to developing in Python.

## In General

### Values

- "Build tools for others that you want to be built for you." - Kenneth Reitz
- "Simplicity is alway better than functionality." - Pieter Hintjens
- "Fit the 90% use-case. Ignore the nay sayers." - Kenneth Reitz
- "Beautiful is better than ugly." - [PEP 20][]
- Build for open source (even for closed source projects).

### General Development Guidelines

- "Explicit is better than implicit" - [PEP 20][]
- "Readability counts." - [PEP 20][]
- "Anybody can fix anything." - [Khan Academy Development Docs][]
- Fix each [broken window](http://www.artima.com/intv/fixit2.html) (bad design, wrong decision, or poor code) *as soon as it is discovered*.
- "Now is better than never." - [PEP 20][]
- Test ruthlessly. Write docs for new features.
- Even more important that Test-Driven Development--*Human-Driven Development*
- These guidelines may--and probably will--change.

## In Particular

### Style

Follow [PEP 8][], when sensible.

#### Naming

- Variables, functions, methods, packages, modules
    - `lower_case_with_underscores`
- Classes and Exceptions
    - `CapWords`
- Protected methods and internal functions
    - `_single_leading_underscore(self, ...)`
- Private methods
    - `__double_leading_underscore(self, ...)`
- Constants
    - `ALL_CAPS_WITH_UNDERSCORES`

###### General Naming Guidelines 

Avoid one-letter variables (esp. `l`, `O`, `I`). 

*Exception*: In very short blocks, when the meaning is clearly visible from the immediate context

**Fine**
```python
for e in elements:
    e.mutate()
```

Avoid redundant labeling.

**Yes**
```python
import audio

core = audio.Core()
controller = audio.Controller()
```

**No**
```python
import audio

core = audio.AudioCore()
controller = audio.AudioController()
```

Prefer "reverse notation".

**Yes**
```python
elements = ...
elements_active = ...
elements_defunct = ...
```

**No**
```python
elements = ...
active_elements = ...
defunct_elements ...
```

Avoid getter and setter methods.

**Yes**
```python
person.age = 42
```

**No**
```python
person.set_age(42)
```

#### Indentation

Use 4 spaces--never tabs. Enough said.

#### Imports

Import entire modules instead of individual symbols within a module. For example, for a top-level module `canteen` that has a file `canteen/sessions.py`,

**Yes**

```python
import canteen
import canteen.sessions
from canteen import sessions
```

**No**

```python
from canteen import get_user  # Symbol from canteen/__init__.py
from canteen.sessions import get_session  # Symbol from canteen/sessions.py
```

*Exception*: For third-party code where documentation explicitly says to import individual symbols.

*Rationale*: Avoids circular imports. See [here](https://sites.google.com/a/khanacademy.org/forge/for-developers/styleguide/python#TOC-Imports).

Put all imports at the top of the page with three sections, each separated by a blank line, in this order:

1. System imports
2. Third-party imports
3. Local source tree imports

*Rationale*: Makes it clear where each module is coming from.

#### Documentation

Follow [PEP 257][]'s docstring guidelines. [reStructured Text](http://docutils.sourceforge.net/docs/user/rst/quickref.html) and [Sphinx](http://sphinx-doc.org/) can help to enforce these standards.

Use one-line docstrings for obvious functions.

```python
"""Return the pathname of ``foo``."""
```

Multiline docstrings should include

- Summary line
- Use case, if appropriate
- Args
- Return type and semantics, unless ``None`` is returned

```python
"""Train a model to classify Foos and Bars.

Usage::

    >>> import klassify
    >>> data = [("green", "foo"), ("orange", "bar")]
    >>> classifier = klassify.train(data)

:param train_data: A list of tuples of the form ``(color, label)``.
:rtype: A :class:`Classifier <Classifier>`
"""
```

Notes

- Use action words ("Return") rather than descriptions ("Returns").
- Document `__init__` methods in the docstring for the class.

```python
class Person(object):
    """A simple representation of a human being.

    :param name: A string, the person's name.
    :param age: An int, the person's age.
    """
    def __init__(self, name, age):
        self.name = name
        self.age = age
```

##### On comments

Use them sparingly. Prefer code readability to writing a lot of comments. Often, small methods are more effective than comments.

*No*

```python
# If the sign is a stop sign
if sign.color == 'red' and sign.sides == 8:
    stop()
```

*Yes*

```python
def is_stop_sign(sign):
    return sign.color == 'red' and sign.sides == 8

if is_stop_sign(sign):
    stop()
```

When you do write comments, remember: "Strunk and White apply." - [PEP 8][]

#### Line lengths

Don't stress over it. 80-100 characters is fine.

Use parentheses for line continuations.

```python
wiki = (
    "The Colt Python is a .357 Magnum caliber revolver formerly manufactured "
    "by Colt's Manufacturing Company of Hartford, Connecticut. It is sometimes "
    'referred to as a "Combat Magnum". It was first introduced in 1955, the '
    "same year as Smith & Wesson's M29 .44 Magnum."
)
```

### Testing

Strive for 100% code coverage, but don't get obsess over the coverage score.

#### General testing guidelines

- Use long, descriptive names. This often obviates the need for doctrings in test methods.
- Tests should be isolated. Don't interact with a real database or network. Use a separate test database that gets torn down or use mock objects.
- Prefer [factories](https://github.com/rbarrois/factory_boy) to fixtures.
- Never let incomplete tests pass, else you run the risk of forgetting about them. Instead, add a placeholder like `assert False, "TODO: finish me"`.

#### Unit Tests

- Focus on one tiny bit of functionality.
- Should be fast, but a slow test is better than no test.
- It often makes sense to have one testcase class for a single class or model.

```python
import unittest
import factories

class PersonTest(unittest.TestCase):
    def setUp(self):
        self.person = factories.PersonFactory()

    def test_has_age_in_dog_years(self):
        self.assertEqual(self.person.dog_years, self.person.age / 7)
```

#### Functional Tests

Functional tests are higher level tests that are closer to how an end-user would interact with your application. They are typically used for web and GUI applications.

- Write tests as scenarios. Testcase and test method names should read like a scenario description.
- Use comments to write out stories, *before writing the test code*.

```python
import unittest

class TestAUser(unittest.TestCase):

    def test_can_write_a_blog_post(self):
        # Goes to the her dashboard
        ...
        # Clicks "New Post"
        ...
        # Fills out the post form
        ...
        # Clicks "Submit"
        ...
        # Can see the new post
        ...
```

Notice how the testcase and test method read together like "Test A User can write a blog post".


## Inspired by...

- [PEP 20 (The Zen of Python)][PEP 20]
- [PEP 8 (Style Guide for Python)][PEP 8]
- [The Hitchiker's Guide to Python][python-guide]
- [Khan Academy Development Docs][]
- [Python Best Practice Patterns][]
- [Pythonic Sensibilities][]
- [The Pragmatic Programmer][]
- and many other bits and bytes

[Pythonic Sensibilities]: http://www.nilunder.com/blog/2013/08/03/pythonic-sensibilities/
[Python Best Practice Patterns]: http://youtu.be/GZNUfkVIHAY
[python-guide]: http://docs.python-guide.org/en/latest/
[PEP 20]: http://www.python.org/dev/peps/pep-0020/
[PEP 257]: http://www.python.org/dev/peps/pep-0257/
[PEP 8]: http://www.python.org/dev/peps/pep-0008/
[Khan Academy Development Docs]: https://sites.google.com/a/khanacademy.org/forge/for-developers
[The Pragmatic Programmer]: http://www.amazon.com/The-Pragmatic-Programmer-Journeyman-Master/dp/020161622X/ref=sr_1_1?ie=UTF8&qid=1381886835&sr=8-1&keywords=pragmatic+programmer

markdown用python开发的“最佳实践最佳”(bobp)指南。(代码片段)

查看详情

markdown用python开发的“最佳实践最佳”(bobp)指南。(代码片段)

查看详情

markdown用python开发的“最佳实践最佳”(bobp)指南。(代码片段)

查看详情

markdown用python开发的“最佳实践最佳”(bobp)指南。(代码片段)

查看详情

markdown用python开发的“最佳实践最佳”(bobp)指南。(代码片段)

查看详情

制作容器镜像的最佳实践(代码片段)

...相关文章总结出来的.包括通用的容器最佳实践,java,nginx,python容器最佳实践.最佳实践的目的一方面保证镜像是可复用的,提升DevOps效率,另一方面是为了提高安全性.希望对各位有所帮助.本文分为四部分内容,分别是:通用容器镜像最... 查看详情

开源监控系统prometheus最佳实践(代码片段)

作者:jimmiehan(韩金明),腾讯PCG后台开发工程师,Prometheus/ThanoscontributorPrometheus是目前最流行的开源监控系统之一,这里以我在基于Prometheus构建天机阁2.0Metrics子系统的实践谈一谈Prometheus的一些最佳实践,最佳实践的理念是Prometheus... 查看详情

什么是rup

...过程。RUP总结了经过多年商业化验证的6条最有效的软件开发经验,这些经验被称为“最佳实践”。“最佳实践”包括,迭代式开发:一种能够通过一系列细化、若干个渐进的反复过程而得出有效解决方案的迭代方法。更容易地... 查看详情

阿里云数据库快速搭建疫情分析系统最佳实践

...时间内完成分析系统搭建,有效助力疫情防控。直达最佳实践:【阿里云数据库快速搭建疫情分析系统最佳实践】最佳实践频道:【最佳实践频道】这里有丰富的企 查看详情

python测试开发django-55.xadmin使用markdown文档编辑器(django-mdeditor)(代码片段)

前言markdown是一个非常好的编辑器,用过的都说好,如果搭建一个博客平台的话,需要在后台做文章编辑,可以整合一个markdown的文本编辑器。github上关于django的markdown插件很多的,看了半天也不知道选哪个好,本篇用django-mdeditor... 查看详情

怎么用c或python读取markdown文件中的信息

参考技术Awithopen('file',r)asf:a=f.read()就可以 查看详情

ubuntu上都有哪些markdown的编辑器

前有那个UberWriter是开源的,Python2的项目,前端是pyGTk,开发者是个德国人[1],为了简洁,没有直接切换字体的功能,中文比较蛋疼,但实际上可以直接到配置文件更改。这个东西原来算是专给Ubuntu写的,往往用Launchpad[2]进行更... 查看详情

python开发的markdown目录提取器,快速将md转思维导图(附gui,可直接下载)(代码片段)

...;我是小小明。最近有不少博主有需求,需要快速提取Markdown文档中的目录并转换为xmind思维导图,据说官方提供了用python直接生成xmind思维导图的方法,但有人反映生成的文件打不开。那么基于这个现状,我将开发... 查看详情

pythonmarkdown干啥用的

参考技术A官方文档说是Markdown2比Markdown更加迅速和完整。用那个的话,你可以自己选择,哪个舒服用哪个。Markdown是一个轻文本标记语言,它允许你在写的时候使用简单文本格式,然后转换为XHTML(HTML)。Python-markdown2是完全用Python实现的... 查看详情

markdown学习

本文学习自简书"Markdown学习?5分钟就够了"1标题标题示例1标题示例22引用用>加句子来实现比如">人生是个含泪的微笑"人生苦短我用Python3代码的引用用tap或者四个空格+代码intmain(){cout<<"hello"<<endl;return0;}4列表4.1无序... 查看详情

slidev:用markdown的方式来做ppt

也许你是一位代码高手,Markdown写作高手,但你是PPT高手吗?你的成绩有没有被PPT高手抢走过呢?不会作精美PPT是不是很头疼呢?今天就给大家介绍了一款PPT制作利器:Slidev~说Slidev之前,咱先聊聊Markdow... 查看详情

slidev:用markdown的方式来做ppt

也许你是一位代码高手,Markdown写作高手,但你是PPT高手吗?你的成绩有没有被PPT高手抢走过呢?不会作精美PPT是不是很头疼呢?今天就给大家介绍了一款PPT制作利器:Slidev~说Slidev之前,咱先聊聊Markdow... 查看详情

c#解析markdown文档,实现替换图片链接操作(代码片段)

...适性的解决方案单独拿出来。我的博客采用程序员最爱的Markdown语法书写,而众所周知markdown有一个缺点就是关联图片资源麻烦因为我的博客需要实现本地用Typora写的Markdown文档导入,所以解析markdown文档并处理导入图片资... 查看详情