Skip to content

Instantly share code, notes, and snippets.

@rduplain
Created September 28, 2011 20:41
Show Gist options
  • Save rduplain/1249199 to your computer and use it in GitHub Desktop.
Save rduplain/1249199 to your computer and use it in GitHub Desktop.
Get a module's docstring in Python without executing it.
import code
def get_module_docstring(filepath):
"Get module-level docstring of Python module at filepath, e.g. 'path/to/file.py'."
co = compile(open(filepath).read(), filepath, 'exec')
if co.co_consts and isinstance(co.co_consts[0], basestring):
docstring = co.co_consts[0]
else:
docstring = None
return docstring
@wimglenn
Copy link

wimglenn commented Nov 13, 2020

My approach:

import ast

with open(filepath) as f:
    doc = ast.get_docstring(ast.parse(f.read()))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment