PyCharm 2023.3 Help

Extract parameter

The Extract Parameter refactoring is used to add a new parameter to a function declaration and to update the function calls accordingly.

Extract a Python parameter in place

The in-place refactorings are enabled in PyCharm by default. So, if you haven't changed this setting, the Extract Parameter refactorings for Python are performed in-place, right in the editor:

  1. In the editor, place the caret within the expression to be replaced by the parameter.

  2. Do one of the following:

    • Press Ctrl+Alt+P.

    • Choose Refactor | Extract | Parameter from the main menu.

    • Choose Refactor | Extract | Parameter from the context menu.

  3. If more than one expression is detected for the current caret position, the Expressions list appears. If this is the case, click the expression to select it. Alternatively, press Up or Down to navigate to the expression of interest, and then press Enter to select it.

    Extract a parameter
  4. Type the parameter name in the box with a red border.

    Enter the parameter name
  5. To complete the refactoring, press Tab or Enter.

    If you haven't completed the refactoring and want to cancel the changes you have made, press Escape.

    Note that sometimes you may need to press the corresponding key more than once.

Extract a parameter using the Extract Parameter dialog

To be able to use the Extract Parameter dialog (instead of performing the refactoring in-place), make sure that the Enable in place refactorings option is off in the editor settings.

Once this is the case, you perform the Extract Parameter refactoring as follows:

  1. In the editor, place the caret within the expression to be replaced by the parameter.

  2. Do one of the following:

    • Press Ctrl+Alt+P.

    • Choose Refactor | Extract | Parameter from the main menu.

    • Choose Refactor | Extract | Parameter from the context menu.

  3. If more than one expression is detected for the current caret position, the Expressions list appears. If this is the case, click the expression to select it. Alternatively, press Up or Down to navigate to the expression of interest, and then press Enter to select it.

  4. In the Extract Parameter dialog that opens:

    1. Specify the parameter name in the Name field.

    2. If more than one occurrence of the expression is found within the function body, you can choose to replace only the selected occurrence or all the found occurrences with the references to the new parameter. Use the Replace all occurrences checkbox to specify your intention.

  5. Preview and apply changes.

Last modified: 07 March 2024