Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:将大型函数分解为段_Python - Fatal编程技术网

Python:将大型函数分解为段

Python:将大型函数分解为段,python,Python,我正在为Reddit创建一个机器人。我目前只有一个非常大的函数,我希望创建子函数,使它更可读 下面是它的大致功能 def replybot(): submissions = reversed(list(subreddit.get_new(limit=MAXPOSTS))) for post in submissions: try: author = post.author.name except AttributeError

我正在为Reddit创建一个机器人。我目前只有一个非常大的函数,我希望创建子函数,使它更可读

下面是它的大致功能

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”在循环中不正确


我有办法做到这一点吗?

如果你把循环的内部部分转换成它自己的函数,它就不在循环中了。对于函数而言,循环中的
continue
等价于
return
(即提前终止此迭代(现在是函数调用)。

如果获取循环的内部部分并将其转换为自己的函数,则它不再在循环中。对于函数而言,循环中的
continue
等价于
return
(即提前终止此迭代(现在是函数调用)。

再次引发错误,而不是尝试继续。或者简单地让它冒泡到主循环,或者如果您需要更好的错误处理,则创建您自己的自定义错误。例如:

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
,这也会截获并隐藏同类错误的所有其他可能来源。

再次引发错误,而不是尝试继续。或者简单地让它冒泡到主循环,或者如果您需要更好的错误处理,则创建您自己的自定义错误。例如:

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
,那么它也会截获并隐藏同类错误的所有其他可能来源。

正如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

正如克劳迪乌所说,当你把内在的命令分解成它自己的功能;它不再在循环中,您的代码将如下所示:

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

但是,
return
是否继续运行(大型)函数的其余部分?我想跳到下一个iteration@Bijan:hmm然后您需要返回一个有意义的值,并检查它,然后
继续
。e、 g.假设你取出的代码片段名为
get_author()
,你可以将
author=post.author.name
替换为
return post.author.name
,而不是
continue
你可以
不返回任何人
。然后在调用代码中,执行
author=get_author()
如果不是author:continue
。但是
是否返回
继续运行(大)函数的其余部分?我想跳到下一个iteration@Bijan:hmm然后您需要返回一个有意义的值,并检查它,然后
继续
。e、 g.假设你取出的代码片段名为
get_author()
,你可以将
author=post.author.name
替换为
return post.author.name
,而不是
continue
你可以
不返回任何人
。然后在调用代码中,执行
author=get_author()
如果不是author:continue
。如果我的代码中有“continue”,我会怎么做?在主循环中,您可以在任何地方使用
continue
。在子函数中,使用
raise MyNotFatalError()
。如果您可以在不是实际错误的条件下继续,可以将异常重命名为更有意义的内容,例如
SkipCurrentPost
如果我的代码中有“continue”,我会怎么做?在主循环中,您可以在任何需要的地方使用
continue
。在子函数中,使用
raise MyNotFatalError()
。如果您可以在并非实际错误的条件下继续,则可以将异常重命名为更有意义的内容,如
SkipCurrentPost