Python中的单独部分

时间:2014-12-04 11:18:02

标签: 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
####

[...]

2 个答案:

答案 0 :(得分:2)

顶级使用模块,在各自的模块中实现单独的部分,然后参考主要部分:

import random
import time

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

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

class Foo:
    def function1():
        pass

class Bar:
    def function2():
        pass

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

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

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

分段使用块

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

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

    xxx.connect(path, port)

Subsublevel 使用空白行和评论

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()

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

答案 1 :(得分:2)

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

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

进一步了解PEP 257以指导您的文档工作。