Python:将大功能分解成段

时间:2015-10-06 17:37:46

标签: python

我正在为Reddit创建一个Bot。我目前只有一个非常大的功能,我希望创建子功能,使其更具可读性。

这是对它的作用的粗略分解

def replybot():
    submissions = reversed(list(subreddit.get_new(limit=MAXPOSTS)))
    for post in submissions:
        try:
            author = post.author.name
        except AttributeError:
            print "AttributeError: Author is deleted"
            continue # Author is deleted. We don't care about this post.
        # DOES PID EXIST IN DB? IF NOT ADD IT
        cur.execute('SELECT * FROM oldposts WHERE ID=?', [pid])
        sql.commit()
        if cur.fetchone(): # Post is already in the database
            continue
        cur.execute('INSERT INTO oldposts VALUES(?)', [pid])
        sql.commit()
...

我希望将代码分解成段,即放入

        try:
            author = post.author.name
        except AttributeError:
            print "AttributeError: Author is deleted"
            continue # Author is deleted. We don't care about this post.

在其自己的功能中,并在replybot()内调用它,但我遇到了调用continue的问题。我得到SyntaxError: 'continue' not properly in loop

我有办法做到这一点吗?

3 个答案:

答案 0 :(得分:3)

如果你采用循环的内部部分并将其转换为自己的函数,它就不再处于循环中。对于函数,循环中continue的等价于return(即,在此期间终止此迭代(现在是函数调用))。

答案 1 :(得分:2)

再次提出错误而不是尝试继续。要么只是让它冒泡到主循环,要么你需要更好的错误处理,自己制作自定义错误。例如:

class MyNotFatalError(Exception):
    pass

def do_something():
    try:
        a, b, c = 1, 2
    except ValueError:
        raise MyNotFatalError('Something went wrong')

# In your main function
for post in submissions:
    try:
        do_something()
        do_some_other_thing()
        do_some_more()
    except MyNotFatalError as err:
        continue # we could print out the error text here
    do_some_last_thing()

这种方式可能更好,因为你只捕获了你想要捕获的错误,并且当有实际错误时仍然让程序崩溃。

如果您只是抓住了ValueError,它也会截取并隐藏同类错误的所有其他可能来源。

答案 2 :(得分:1)

正如Claudiu所说,当你将内部命令分解为它自己的功能时;它不再在循环中,您的代码将如下所示:

def isNotAuthorDeleted(post):
    try:
        author = post.author.name
        return author 
    except AttributeError:
        print "AttributeError: Author is deleted"
        return false

你的循环将是:

for post in submissions:
    if not isNotAuthorDeleted(post):
        continue