最近读github上的源码时看到有类似的函数定义形式.
def search(self, criteria: str or bytes = 'ALL', charset: str = 'US-ASCII') -> [str]: """ Search mailbox for matching message numbers (this is not uids) :param criteria: message search criteria (see examples at ./doc/imap_search_criteria.txt) :param charset: IANA charset, indicates charset of the strings that appear in the search criteria. See rfc2978 :return list of str """ encoded_criteria = criteria if type(criteria) is bytes else str(criteria).encode(charset) search_result = self.box.search(charset, encoded_criteria) check_command_status(search_result, MailboxSearchError) return search_result[1][0].decode().split() if search_result[1][0] else []
留意函数定义哪一行, 出现了参数名加冒号, 括号外还有-> [str] , 不太懂,于是查了查python的手册.
手册地址: https://docs.python.org/zh-cn/3/library/typing.html?highlight=%E5%87%BD%E6%95%B0%20%E6%B3%A8%E9%87%8A#module-typing
发现为Python3.5的新增功能,用途为对函数的参数变量类型进行提示,还可以对返回结果的变量类型进行提示. 这个功能进一步增强了代码可读性, 特此记下来.
完整的说明在这个链接: https://www.python.org/dev/peps/pep-0484/