整合在一起
一旦對象被導入,我們可以開始檢測了。這是一個簡單的例子,重復調(diào)用 getmembers(object, filter),過濾器是一個有用的 is 函數(shù)。你能夠發(fā)現(xiàn) isclass 和 isfunction,其它相關的方法都是 is開頭的,例如,ismethod , isgenerator , iscoroutine。這都取決于你是否想寫一些通用的,可以處理所有的特殊情況,或一些更小的和更特殊的源代碼。我堅持前兩點,因為我不用把采用3個不同方法來創(chuàng)建我想要的格式化模塊,類和功能。
def getmarkdown(module): output = [ module_header ] output.extend(getfunctions(module) output.append("***\n") output.extend(getclasses(module)) return "".join(output)def getclasses(item): output = list() for cl in inspect.getmembers(item, inspect.isclass): if cl[0] != "__class__" and not cl[0].startswith("_"): # Consider anything that starts with _ private # and don't document it output.append( class_header ) output.append(cl[0]) # Get the docstring output.append(inspect.getdoc(cl[1]) # Get the functions output.extend(getfunctions(cl[1])) # Recurse into any subclasses output.extend(getclasses(cl[1]) return outputdef getfunctions(item): for func in inspect.getmembers(item, inspect.isfunction): output.append( function_header ) output.append(func[0]) # Get the signature output.append("\n```python\n) output.append(func[0]) output.append(str(inspect.signature(func[1])) # Get the docstring output.append(inspect.getdoc(func[1]) return output
當要格式化大文本和一些編程代碼的混合體時,我傾向于把它作為一個在列表或元組中的獨立項目,用 "".join() 來合并輸出。在寫作的時候,這種方法其實比基于插值的方法(.format 和 %)更快。然而,python 3.6 的新字符串格式化將比這更快,更具可讀性。