Extract Method
Basics
When the Extract Method refactoring is invoked , PyCharm analyses the selected block of code and detects variables that are the input for the selected code fragment and the variables that are output for it.
The detected output variable is used as a return value for the extracted function.
Examples
JavaScript example
Before | After |
---|---|
function multiplication(a,b) {
c = a + b;
d = c * c;
return d;
} |
function sum(a,b);
return a + b;
function multiplication(a,b) {
c = sum(a,b);
d = c * c;
return d;
} |
Python Extract Method example
Extracting a method
To extract a method, follow these steps
- In the editor, select a block of code to be transformed into a method or a function.
- On the main menu or on the context menu of the selection, choose or press Ctrl+Alt+M.
- In the Extract Method dialog box that opens, specify the name of the new function.
- In the Parameters area, do the following:
- Check the result in the Signature Preview pane and click OK
to create the required function.
The selected code fragment will be replaced with a function call.
Processing duplicates
If duplicate code fragments are encountered, PyCharm suggests to replace them with the calls to the extracted method:

See Also
Reference:
Last modified: 23 November 2016