I've written a little library that uses the builtin ast library to convert between functions, docstrings, argparse .add_argument, classes, and [soon] more.

Stubs look something like this, with ir referring to 'intermediate representation'; i.e., a common internal data-structure that everything parses to and emits from:

def argparse_to_ir
def class_to_ir
def docstring_to_ir
def function_to_ir
# Actually had roundtrip ones also
# like `def argparse2class`


def ir_to_argparse
def ir_to_class

Earlier today I refactored these for readability and usability. One I reworked into a module called ir.py, and renamed the functions so you would do import ir followed by ir.from_argparse.

The other I tried the more class-based OO style, had a base ABC class with to_argparse, to_class, &etc.; and specialised with a new class for each type that just created a new def __init__ with different parameters (based on input). So now you do:

ArgparseTransformer(argparse_ast, **common_kwargs).to_class()  # `.to_argparse()`
ClassTransformer(class_def_ast, **common_kwargs).to_class()    # or `.to_method()`

PS: There is no need for a unified interface to infer what the input type is.

Which approach is better, the [explosion of] classes one, or the one which requires knowledge of the internal data-structure?

PPS: Open to alternative 3rd+ choices!

1 Answer 1


Ended up removing all classes in my codebase—outside of unittest.TestCase)—and just using defs:

In [1]: import doctrans.transformers
In [2]: doctrans.transformers.__all__
Out[3]: ['to_argparse_function', 'to_class', 'to_docstring',
         'to_file', 'to_function']
In [4]: import doctrans.docstring_struct
In [5]: doctrans.docstring_struct.__all__
Out[6]: ['from_class', 'from_class_with_method', 'from_function',
         'from_argparse_ast', 'from_docstring', 'from_docstring_parser']

Leaving me with an SDK like:

            class_with_method_and_body_types_ast, "method_name"
    filename='classy.py', skip_black=False)

(obviously I need a better name than docstring_struct)

Which works reasonably well…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.