Converter implementation in Python: class versus module?
https://softwareengineering.stackexchange.com/questions/413097
-
14-03-2021 - |
Domanda
I've written a little library that uses the builtin ast
library to convert between functions, docstrings, argparse .add_argument
, class
es, 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`
Similarly:
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] class
es one, or the one which requires knowledge of the internal data-structure?
PPS: Open to alternative 3rd+ choices!
Soluzione
Ended up removing all class
es in my codebase—outside of unittest.TestCase
)—and just using def
s:
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:
transformers.to_file(
transformers.to_function(
docstring_struct.from_class_with_method(
class_with_method_and_body_types_ast, "method_name"
),
emit_default_doc=False,
function_name="method_name",
function_type="self"
)
filename='classy.py', skip_black=False)
)
(obviously I need a better name than docstring_struct
)
Which works reasonably well…