Docstring for variable

前端 未结 9 1908
予麋鹿
予麋鹿 2021-01-31 13:35

Is it posible to use docstring for plain variable? For example I have module called t

def f():
    \"\"\"f\"\"\"

l = lambda x: x
\"\"\"l\"\"\"
         


        
9条回答
  •  孤城傲影
    2021-01-31 14:07

    Well, even though Python does not treat strings defined immediately after a global definition as a docstring for the variable, sphinx does and it is certainly not a bad practice to include them.

    debug = False
    '''Set to True to turn on debugging mode. This enables opening IPython on 
    exceptions.
    '''
    

    Here is some code that will scan a module and pull out names of global variable definitions, the value and a docstring that follows.

    def GetVarDocs(fname):
        '''Read the module referenced in fname (often .__file__) and return a
        dict with global variables, their value and the "docstring" that follows
        the definition of the variable
        '''
        import ast,os
        fname = os.path.splitext(fname)[0]+'.py' # convert .pyc to .py
        with open(fname, 'r') as f:
            fstr = f.read()
        d = {}
        key = None
        for node in ast.walk(ast.parse(fstr)):
            if isinstance(node,ast.Assign):
                key = node.targets[0].id
                d[key] = [node.value.id,'']
                continue
            elif isinstance(node,ast.Expr) and key:
                d[key][1] = node.value.s.strip()
            key = None
        return d
    

提交回复
热议问题