Skip to content

Instantly share code, notes, and snippets.

@podhmo
Last active July 14, 2019 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save podhmo/3e7aca70b6411a27556ea4b2487e3d97 to your computer and use it in GitHub Desktop.
Save podhmo/3e7aca70b6411a27556ea4b2487e3d97 to your computer and use it in GitHub Desktop.
f0
f1 summary
f2 summary
f3 summary
f4 summary
f5 summary
A summary
import inspect
from magicalimport import import_module
from handofcats import as_command
def get_summary(doc):
if not doc:
return doc
return doc.split("\n\n", 1)[0]
@as_command
def run(pkg: str) -> None:
m = import_module(pkg)
for name, v in m.__dict__.items():
if inspect.isfunction(v) or inspect.isclass(v):
if v.__module__ == m.__name__:
print(f"{name} {get_summary(inspect.getdoc(v) or '')}")
f0
f1 summary
f2 summary
f3 summary
f4 summary
f5 summary
A summary
import typing as t
import inspect
from pyinspect.code.parse import parse_file, PyTreeVisitor, Node, node_name, token
from handofcats import as_command
def get_summary(doc):
if not doc:
return doc
return doc.split("\n\n", 1)[0]
class Visitor(PyTreeVisitor):
def visit_funcdef(self, node: Node):
print(f"{get_name(node)} {get_summary(get_doc(node) or '')}")
def visit_classdef(self, node: Node):
print(f"{get_name(node)} {get_summary(get_doc(node) or '')}")
def get_name(node: Node) -> t.Optional[str]:
assert node_name(node) in ("funcdef", "classdef", "async_funcdef")
for x in node.children[1:]:
if x.type == token.NAME:
return x.value
return None
def get_doc(node: Node) -> t.Optional[str]:
assert node_name(node) in ("funcdef", "classdef", "async_funcdef")
suite = None
for x in node.children:
if node_name(x) == "suite":
suite = x
break
else:
return None
for x in suite.children[2:]:
if node_name(x) == "simple_stmt":
if x.children[0].type == token.STRING:
return inspect.cleandoc(x.children[0].value.strip("""\n"'"""))
return None
@as_command
def run(filename: str) -> None:
t = parse_file(filename)
v = Visitor()
v.visit(t)
_get_fields Get fields from a class. If ordered=True, fields will sorted by creation index.
_get_fields_by_mro Collect fields from a class, following its method resolution order. The
class itself is excluded from the search; only its parents are checked. Get
fields from ``_declared_fields`` if available, else use ``__dict__``.
SchemaMeta Metaclass for the Schema class. Binds the declared fields to
a ``_declared_fields`` attribute, which is a dictionary mapping attribute
names to field objects. Also sets the ``opts`` class attribute, which is
the Schema class's ``class Meta`` options.
SchemaOpts class Meta options for the :class:`Schema`. Defines defaults.
BaseSchema Base schema class with which to define custom schemas.
Schema Base schema class with which to define custom schemas.
_get_fields Get fields from a class. If ordered=True, fields will sorted by creation index.
_get_fields_by_mro Collect fields from a class, following its method resolution order. The
class itself is excluded from the search; only its parents are checked. Get
fields from ``_declared_fields`` if available, else use ``__dict__``.
SchemaMeta Metaclass for the Schema class. Binds the declared fields to
a ``_declared_fields`` attribute, which is a dictionary mapping attribute
names to field objects. Also sets the ``opts`` class attribute, which is
the Schema class's ``class Meta`` options.
SchemaOpts class Meta options for the :class:`Schema`. Defines defaults.
BaseSchema Base schema class with which to define custom schemas.
Schema
Address Address(host, port)
URL
URLPath A URL path string that may also hold an associated protocol and/or host.
Used by the routing to return `url_path_for` matches.
Secret Holds a string value that should not be revealed in tracebacks etc.
You should cast the value to `str` at the point it is required.
CommaSeparatedStrings All the operations on a read-only sequence.
ImmutableMultiDict Abstract base class for generic types.
MultiDict Abstract base class for generic types.
QueryParams An immutable multidict.
UploadFile An uploaded file included as part of the request data.
FormData An immutable multidict, containing both file uploads and text input.
Headers An immutable, case-insensitive multidict.
MutableHeaders An immutable, case-insensitive multidict.
URL
URLPath A URL path string that may also hold an associated protocol and/or host.
Used by the routing to return `url_path_for` matches.
Secret Holds a string value that should not be revealed in tracebacks etc.
You should cast the value to `str` at the point it is required.
CommaSeparatedStrings
ImmutableMultiDict
MultiDict
QueryParams An immutable multidict.
UploadFile An uploaded file included as part of the request data.
FormData An immutable multidict, containing both file uploads and text input.
Headers An immutable, case-insensitive multidict.
MutableHeaders
_AttributeHolder Abstract base class that provides __repr__.
_copy_items
HelpFormatter Formatter for generating usage messages and argument help strings.
RawDescriptionHelpFormatter Help message formatter which retains any formatting in descriptions.
RawTextHelpFormatter Help message formatter which retains formatting of all help text.
ArgumentDefaultsHelpFormatter Help message formatter which adds default values to argument help.
MetavarTypeHelpFormatter Help message formatter which uses the argument 'type' as the default
metavar value (instead of the argument 'dest')
_get_action_name
ArgumentError An error from creating or using an argument (optional or positional).
ArgumentTypeError An error from trying to convert a command line string to a type.
Action Information about how to convert command line strings to Python objects.
_StoreAction Information about how to convert command line strings to Python objects.
_StoreConstAction Information about how to convert command line strings to Python objects.
_StoreTrueAction Information about how to convert command line strings to Python objects.
_StoreFalseAction Information about how to convert command line strings to Python objects.
_AppendAction Information about how to convert command line strings to Python objects.
_AppendConstAction Information about how to convert command line strings to Python objects.
_CountAction Information about how to convert command line strings to Python objects.
_HelpAction Information about how to convert command line strings to Python objects.
_VersionAction Information about how to convert command line strings to Python objects.
_SubParsersAction Information about how to convert command line strings to Python objects.
FileType Factory for creating file object types
Namespace Simple object for storing attributes.
_ActionsContainer
_ArgumentGroup
_MutuallyExclusiveGroup
ArgumentParser Object for parsing command line strings into Python objects.
_AttributeHolder Abstract base class that provides __repr__.
_copy_items
HelpFormatter Formatter for generating usage messages and argument help strings.
RawDescriptionHelpFormatter Help message formatter which retains any formatting in descriptions.
RawTextHelpFormatter Help message formatter which retains formatting of all help text.
ArgumentDefaultsHelpFormatter Help message formatter which adds default values to argument help.
MetavarTypeHelpFormatter Help message formatter which uses the argument 'type' as the default
metavar value (instead of the argument 'dest')
_get_action_name
ArgumentError An error from creating or using an argument (optional or positional).
ArgumentTypeError An error from trying to convert a command line string to a type.
Action Information about how to convert command line strings to Python objects.
_StoreAction
_StoreConstAction
_StoreTrueAction
_StoreFalseAction
_AppendAction
_AppendConstAction
_CountAction
_HelpAction
_VersionAction
_SubParsersAction
FileType Factory for creating file object types
Namespace Simple object for storing attributes.
_ActionsContainer
_ArgumentGroup
_MutuallyExclusiveGroup
ArgumentParser Object for parsing command line strings into Python objects.
default: 00 01 02 03 04 05 06 07
00:
python 00*.py ./target.py | tee $@.output
01:
python 01*.py ./target.py | tee $@.output
02:
python 00*.py marshmallow.schema | tee $@.output
03:
python 01*.py $$(pyinspect resolve marshmallow.schema) | tee $@.output
04:
python 00*.py starlette.datastructures | tee $@.output
05:
python 01*.py $$(pyinspect resolve starlette.datastructures) | tee $@.output
06:
python 00*.py argparse | tee $@.output
07:
python 01*.py $$(pyinspect resolve argparse) | tee $@.output
def f0():
print("hai")
def f1():
"""summary"""
print("hai")
def f2():
"""
summary
"""
print("hai")
def f3():
"""
summary
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
"""
print("hai")
def f4():
"""
summary
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
"""
print("hai")
def f5(x: str):
"""
summary
"""
print("hai")
class A:
"""summary"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment