Wing Tips: Introducing Functions and Methods with Refactoring in Wing Pro

Jul 22, 2019

In this issue of Wing Tips we explain how to quickly create new functions and methods out of existing blocks of Python code, using Wing Pro's Extract Method/Function refactoring operation.

This is useful whenever you have some existing code that you want to reuse in other places, or in cases where code gets out of hand and needs to be split up to make it more readable, testable, and maintainable.

Wing supports extracting functions and methods for any selected code, so long as that code does not contain return or yield statements. In that case automatic extraction is not possible, since Wing cannot determine how the extracted function should be called from or interact with the original code.


Here's a simple example that extracts several lines of code for reuse elsewhere:


Shown Above: Select code to extract, right-click to initiate Extract Function / Method, enter test_extract as the function name, select local nested function as the extraction type, then highlight the extracted point of call, and go to definition of the new nested function.

Notice that when the code is extracted, Wing takes care of adding the necessary arguments and return values and places an invocation of the new method or function into the original context. This is done in a way that does not alter the functionality of the code, even though it has been restructured.

Try It Yourself

You can easily try this out in your copy of Wing Pro, by selecting some lines in your Python code base, and choosing Extract Method/Function from the Refactor menu. As in the above example, you will be asked to enter a name and choose whether to place the extracted code into a function at the top level of the module, in a method in the current class, or in a nested function in the current method or function. An unwanted extraction can be backed out with the Revert button in the Refactoring tool.

If you want to move the code to some other module or class, you can do this after initially extracting it by using the Move Symbol operation in the Refactor menu. We'll take a look at that next time.

That's it for now! We'll be back soon with more Wing Tips for Wing Python IDE.

Share this article: