PyCharm 2025.2 Help

Introduce Variable

If you come across an expression that is hard to understand, or it is duplicated in several places throughout your code, the Introduce Variable refactoring Ctrl+Alt+V can help you deal with those problems by placing the result of such expression or its part into a separate variable that is less complex and easier to understand. Plus, it reduces the code duplication.

Introduce a variable in place

  1. In the editor, select an expression or its part that you want to introduce. You can also place the caret within the expression, in this case PyCharm offers you a list of potential code selections.

  2. Press Ctrl+Alt+V or go to Refactor | Extract/Introduce | Variable in the main menu. Alternatively, right-click and choose Refactor | Introduce Variable 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, use the Up and Down arrow keys to navigate to the expression of interest and then press Enter to select it.

    Select expression
  4. If more than one occurrence of the expression is found, specify whether you wish to replace only the selected occurrence, or all the found occurrences.

    Introduce variable occurrences scope
  5. Select a name suggested in the popup or type your own and press Enter.

    Extracting a variable

Extract a variable using the dialog

By default, PyCharm uses the in-place refactoring. To use the dialog for the refactoring, open the Settings dialog (Ctrl+Alt+S) , go to Editor | Code Editing, and select the In modal dialogs refactoring option in the Refactorings area.

Disable in-place refactorings
  1. In the editor, select an expression or its part that you want to introduce as a variable.

  2. Press Ctrl+Alt+V or go to Refactor | Extract/Introduce | Variable in the main menu. Alternatively, select Refactor | Introduce Variable from the context menu.

  3. In the Extract Variable dialog that opens, specify the name of the new constant.

    Extract Variable Dialog
  4. To automatically replace all occurrences of the selected expression (if it is found more than once), select the option Replace all occurrences.

  5. Click OK to create the constant.

24 July 2025