Python 中的单独部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27292698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:37:27  来源:igfitidea点击:

Separate sections in Python

python

提问by Edgar Derby

I was wondering whether there is a best practiceto separate chunks of code in Python. In MATLAB, for example, two comment signs (%%) create a code section. At the moment, I am doing:

我想知道是否有在 Python 中分离代码块的最佳实践。例如,在 MATLAB 中,两个注释符号 ( %%) 创建一个代码段。目前,我正在做:

####
## Import libraries
####

import _mssql #Binary here: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql

####
## Connect to db + Query the data
####

q_file = open ("query.txt", "r")
query = q_file.read().replace('\n', '')

##Connect to the database
conn = _mssql.connect(server='', user='',
                      password='', database='')

##Query the database
conn.execute_query(query)
for row in conn:
    print(row)

####
## Data filtering
####

[...]

回答by Dima Tisnek

Top leveluse modules, implement separate parts in their respective modules, then refer to those in your main:

顶层使用模块,在各自的模块中实现单独的部分,然后在你的主要部分中引用:

import random
import time

if time.time() > random.random():
    pass

Next level(optional, use sparingly) use classes

下一级(可选,谨慎使用)使用类

class Foo:
    def function1():
        pass

class Bar:
    def function2():
        pass

Next level, what you need, use functions

下一层,你需要什么,使用函数

def connect(...):
    filename = ...
    params = ...(filename)
    return mysql.connect(*params)

def mainloop(...):
    for xx in connect():
        pass

Subleveluse blocks

子级使用块

def foo(path=None, port=None):
    if not path:
        filename = ...
        path = ...(filename)

    if not port:
        foobar = ...
        port = ...(foobar)

    xxx.connect(path, port)

Subsubleveluse blank lines and comments

子级使用空行和注释

def foo(...):
    bar.bar()

    assert path  # <-- this is essentially a comment
    smth_with(path)
    some_other()
    data = xxx.yyy()

    assert data
    foo = blahblah
    bar = lambda: blahblah
    filtered = filter(yada, data)

    # data is clean at this point  # <-- an actual comment
    for x, y in data:
        foo.bar.baz()

Final thoughtslarge comment blocks like in OQ show "code smell." You are right to start wondering how to organise your code at this point :)

最后的想法像 OQ 中的大注释块显示“代码异味”。您现在开始想知道如何组织您的代码是正确的:)

回答by tripleee

Python quite naturally offers a modular structure, and documentation strings for every level of structure.

Python 很自然地提供了模块化结构,以及每个结构级别的文档字符串。

Your comments generally would belong as function names or method descriptions. Then the code reads naturally. (Some comments are so obvious as to be useless, like "Import libraries".)

您的评论通常属于函数名称或方法描述。然后代码自然阅读。(有些注释太明显了以至于没用,比如“导入库”。)

"""
Perform stuff.  Obviously this documentation should be more specific in reality.
"""

import _mssql  # Binary here: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql


def run_query(filename):
    """
    Open connection to database, run the query in the file, and
    return rows as a list.
    """
    rows = []

    # Minor tweak: "with" takes care of closing the file when you're done
    with open (filename, "r") as q_file:
        query = q_file.read().replace('\n', '')

    conn = _mssql.connect(server='', user='',
                      password='', database='')

    conn.execute_query(query)
    for row in conn:
        # Maybe use yield here instead of reading all the results into memory
        rows.append(row)

    return rows

def filter(rows):
    """
    Filter a list of rows: Remove any rows containing 'Albuquerque'.
    """
    # ....

results = filter(run_query("query.txt"))

See further PEP 257to guide your documentation efforts.

请参阅更多PEP 257以指导您的文档工作。