我正在为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
我有办法做到这一点吗?你知道吗
正如Claudiu所说,当您将内部命令分解到它自己的函数中时;它不再在循环中,您的代码将如下所示:
你的循环是:
如果你把一个循环的内部部分转换成它自己的函数,它就不再是一个循环了。对于函数,循环中
continue
的等价物是return
(即提前终止此迭代(现在是函数调用)。你知道吗再次引发错误,而不是尝试继续。或者简单地让它冒泡到主循环,或者如果您需要更好的错误处理,那么创建您自己的自定义错误。例如:
这样可能更好,因为您只捕获您知道要捕获的错误,并且在出现实际错误时仍然让程序崩溃。你知道吗
如果您只是捕获了
ValueError
,那么它也会截获并隐藏同一类错误的所有其他可能来源。你知道吗相关问题 更多 >
编程相关推荐