如何从函数或方法返回'pass'?



我创建了一个方法,将句子拆分为单词,并返回句子的第一个单词(您可以使用NLTK tokenizerargparse,但由于这是一个用于学习Python的类项目,我从头开始创建了一种简单的标记化器)该方法还有一个有用的"help"参数,在该参数中传递-h--help将显示帮助文本。但是,如果用户传递-h或--help,我希望函数输出帮助文本,然后输出"break"或"pass"。这是我的方法:

class example_method(object):
def __init__(self):
self.data = []
def parse(self, message):
if(("-h" or "--help") in message): 
print("This is a helpful message")
else:
self.data = [x.strip() for x in message.split(' ')]
return self.data

如果用户输入一条常规消息,则该方法有效。让我举例说明:

example = example_method()
input_message = "Hello there how are you?"
print(example.parse(input_message)[0])

以上操作效果良好。但是,如果用户输入-h或--help,该方法将返回一个错误:

example = example_method()
input_message = "--help"
print(example.parse(input_message)[0])

以上将返回:TypeError: 'NoneType' object is not subscriptable我意识到一个可能的解决方案是:

try: print(example.parse(input_message)[0])
except: pass

但是有没有办法从这样的方法中返回pass

def parse(self, message):
if(("-h" or "--help") in message): 
print("This is a helpful message")
return pass
else:
self.data = [x.strip() for x in message.split(' ')]
return self.data

我的目标是我不想要错误消息,因为这个方法是一个更大程序的一部分,错误只会让输出看起来很难看。如果该方法输出帮助文本,然后在没有错误的情况下退出,那么它看起来会更加专业。

也许只需要安排parse函数返回None,那么调用函数就可以检查并处理这种情况…

例如:

class example_method(object):
# …
def parse(self, message):
if message in {"-h", "--help"}:
print("This is a helpful message")
return  # implicitly returns None
self.data = [x.strip() for x in message.split(' ')]
return self.data
res = example.parse(input_message)
if res is None:
return
print(res[0])

您可以使用exit()立即停止程序执行。

def parse(self, message):
if(("-h" or "--help") in message): 
print("This is a helpful message")
exit()
else:
self.data = [x.strip() for x in message.split(' ')]
return self.data

考虑使用argparse自动生成-h--help标志以及帮助文本。

低成本演示:

script.py

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-p', help='This will be printed')
args = parser.parse_args()
print(args.p)

用法:

$ python3 script.py -p hello
hello
$ python3 script.py -h
usage: script.py [-h] [-p P]
optional arguments:
-h, --help  show this help message and exit
-p P        This will be printed

如您所见,使用-h(或--help)将显示帮助消息,并且不执行任何其他代码(默认情况下)。

你应该过度思考你的设计。。。添加

def help(self): 
print("Cool description")

方法,并从def parse(self, message)中删除"帮助切换解析"。

您正在削弱解析器的功能。。。考虑一下解析这个完全后悔的消息:

"Paris is a cool town-however you travel it: by foot, by bike or by parachute." 

参见SRP(单一责任原则)-parse不应打印帮助消息。


您也可以使用文档提供help():

class well_documented_example_class(object):
"""Totally well documented class"""
def parse(self, message):
"""This method does coool things with your 'message'
'message' : a string with text in it to be parsed"""
self.data = [x.strip() for x in message.split(' ')]
return self.data

您可以通过发布获得帮助

print(help(well_documented_example_class))

获取:

class well_documented_example_class(builtins.object)
|  Totally well documented class
|  
|  Methods defined here:
|  
|  parse(self, message)
|      This method does coool things with your 'message'
|      
|      'message' : a string with text in it to be parsed
|  
|  ----------------------------------------------------------------------
|  Data descriptors defined here:
|  
|  __dict__
|      dictionary for instance variables (if defined)
|  
|  __weakref__
|      list of weak references to the object (if defined)

感谢您的建议,我创建了自己的命令解析模块来解决这个问题。你可以在GitHub上找到它:https://github.com/MonkeyBot2020/comparse

以下是它的一些用法示例:

from comparse import comparse
query = comparse(False)
query.add_argument("log_channel", "str", "logs.txt", "Logs the channel in specified file. DEFAULT ARGUMENT(S): log_channel 'logs.txt'")
query.add_argument("content_filter", "str", "None", "Filter log by content. DEFAULT ARGUMENT(S): content_filter 'None'")
query.add_argument("log_attachments", "bool", True, "Logs attachments. DEFAULT ARGUMENT(S): log_attachments 'True'")
query.add_argument("log_author", "bool", False, "Logs author of message. DEFAULT ARGUMENT(S): log_author=False")
query.add_argument("exclude_content", "str", "None", "Exclude content from log. DEFAULT ARGUMENT(S): exclude_content='None'")
#FIRST EXAMPLE
message = "log_channel --h"
file_name = query.parse(message)
try: print(file_name['exclude_content'][0])
except: print(query.parse("--help"))
#SECOND EXAMPLE
message = "log_channel=example.txt, content_filter=posted, log_attachments=True, log_author=True, exclude_content='apple, pear, orange'"
file_name = query.parse(message)
try: print(file_name)
except: print(query.parse("--help"))
#THIRD EXAMPLE
message = "log_channel, exclude_content='apple, pear'"
file_name = query.parse(message)
try: print(file_name['exclude_content'])
except: print(query.parse("--help"))
#FOURTH EXAMPLE
message = "i made a booboo"
file_name = query.parse(message)
try: print(file_name['mistaken_content'][0])
except: print(query.parse("--help"))

希望这是有用的:)

最新更新