Moving a function from one file to another, inserting it into a given function/class: simple in theory...
mvdef began as a 'meta-code' tool (Python has others like
Black/isort though these serve
more 'housekeeping' purposes).
The project uses two different libraries for AST handling, astor ("AST observe/rewrite") and asttokens. The latter was required to find the AST end points, though it contained a peculiar bug
The project was tricky to start (initially I focused too much on colourfully logging, to clarify the somewhat complicated model of what was going on in seemingly simple usages) but after a break in development (of around an entire year) I improved the command line interface with multiple entrypoints for moving/copying classes and functions.
- You can get an overview of how the features progressed by looking at the releases
It may have been wiser to delegate import parsing to a library such as
isort (though I do note
that not all libraries can use isort, some rely on fixed import order in a kind of race condition).
It may also have been possible to delegate
handling (or funcdef/classdef path identification, PEP 3155)
to Sphinx (which seems to
do so here)
-- but equally it's informative to code such things yourself, to just the level of detail you need.
In hindsight, my initial approach of testing through a single 'demo' was misguided, and I clearly should have written to test in a more conventional style (I became much keener on Test Driven Development during 2020). To my mind at the time, it was not the type of library suitable to traditional unit testing, but in fact Black gives an example of a library which acts on code and uses data files in its test directory.
Such a tool requires a more serious test suite, as many failure modes only show up in more complex scripts (not something I'd foreseen).
Lastly, vim integration is something I'm yet to pursue on this library but would be ideal if it's to be a true developer velocity aid.
- I later discovered vim's maximum clipboard length can be increased, and now use this day-to-day, but of course still leaves me needing to handle imports manually, which should not be something a dev needs to consider.
This project was a proof-of-concept, and I don't consider it fully proven, so I didn't go to the lengths of documenting it in Sphinx, but if/when it does progress to that stage I'll do so.
For me, a boon of doing this was having no illusions about what's in the AST any more, how imports work, and all the different combinations of nesting (I'd not encountered the phrase 'inner class' before). It was also nice to 'rescue' this package from the doldrums after a break in development, and to appreciate the versatility of unit testing for software that acts in a different way than I'm used to considering how to test for.