Mapping module imports in Python for easy refactoring

前端 未结 4 463
逝去的感伤
逝去的感伤 2021-02-07 10:40

I have a bunch of Python modules I want to clean up, reorganize and refactor (there\'s some duplicate code, some unused code ...), and I\'m wondering if there\'s a tool to make

4条回答
  •  北荒
    北荒 (楼主)
    2021-02-07 11:34

    Writing a script that does this probably wouldn't be very complicated (though there are different syntaxes for import to handle),

    It's trivial. There's import and from module import. Two syntax to handle.

    Do you know of a more exact term for what I'm trying to do? Code reorganization?

    Design. It's called design. Yes, you're refactoring an existing design, but...

    Rule One

    Don't start a design effort with what you have. If you do, you'll only "nibble around the edges" making small and sometimes inconsequential changes.

    Rule Two

    Start a design effort with what you should have had if you'd only been smarter. Think broadly and clearly about what you're really supposed to be doing. Ignore what you did.

    Rule Three

    Design from the ground up (or de novo as some folks say) with the correct package and module architecture.

    Create a separate project for this.

    Rule Four

    Test First. Write unit tests for your new architecture. If you have existing unit tests, copy them into the new project. Modify the imports to reflect the new architecture and rewrite the tests to express your glorious new simplification.

    All the tests fail, because you haven't moved any code. That's a good thing.

    Rule Five

    Move code into the new structure last. Stop moving code when the tests pass.

    You don't need to analyze imports to do this, BTW. You're just using grep to find modules and classes. The old imports and the tangled relationships among the old imports doesn't matter, and doesn't need to be analyzed. You're throwing it away. You don't need tools smarter than grep.

    If feel an urge to move code, you must be very disciplined. (1) you must have test(s) which fail and then (2) you can move some code to pass the failing test(s).

提交回复
热议问题