Python中的单独部分

Edg*_*rby 22 python

我想知道是否有最佳实践来分离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
####

[...]
Run Code Online (Sandbox Code Playgroud)

tri*_*eee 7

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

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

"""
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(rows):
    """
    Filter a list of rows: Remove any rows containing 'Albuquerque'.
    """
    # ....

results = filter_rows(run_query("query.txt"))
Run Code Online (Sandbox Code Playgroud)

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


Dim*_*nek 5

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

import random
import time

if time.time() > random.random():
    pass
Run Code Online (Sandbox Code Playgroud)

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

class Foo:
    def function1():
        pass

class Bar:
    def function2():
        pass
Run Code Online (Sandbox Code Playgroud)

下一级别,您需要使用的功能

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

def mainloop(...):
    for xx in connect():
        pass
Run Code Online (Sandbox Code Playgroud)

子级使用块

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

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

    xxx.connect(path, port)
Run Code Online (Sandbox Code Playgroud)

子级别使用空白行和注释

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()
Run Code Online (Sandbox Code Playgroud)

最终想法(如OQ中的大注释块)显示“代码异味”。您现在就开始想知道如何组织代码了:)