PyCharm Edu 4.0 Help

Extract Constant

Basics

The Extract Constant refactoring makes your source code easier to read and maintain. It also helps you avoid using hard-coded constants without any explanations about their values or purpose.

Example

BeforeAfter
import math class Solver: def demo(self): a = 3 b = 25 c = 46 root1 = (-b + math.sqrt(b**2 - 4*c)) / (2*a) root2 = (-b - math.sqrt(b**2 - 4*c)) / (2*a) print (root1, root2) Solver().demo()
import math RETURN_TYPE_OF_SQRT = math.sqrt(b**2 - 4*a*c) class Solver: def demo(self): a = 3 b = 25 c = 52 root1 = (-b + RETURN_TYPE_OF_SQRT) / (2*a) root2 = (-b - RETURN_TYPE_OF_SQRT) / (2*a) print(root1, root2) Solver().demo()
/help/img/idea/2017.2/py_extract_substring1.png
/help/img/idea/2017.2/py_extract_substring_constant.png

Extracting a Python constant in-place

To extract a Python constant in-place

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

  1. Place the cursor within the expression or declaration of a variable to be replaced by a constant.
  2. Do one of the following:
    • PressCtrl+Alt+C.
    • Choose Refactor | Extract | Constant on the context menu.
  3. If more than one expression is detected for the current cursor position, the Expressions list appears. If this is the case, select the required expression. To do that, click the expression. Alternatively, use the Up and Down arrow keys to navigate to the expression of interest, and then press Enter to select it.
    /help/img/idea/2017.2/IntroduceConstant_Python_InPlace_SelectExpression.png
  4. If more than one occurrence of the expression is found within the class, specify whether you wish to replace only the selected occurrence, or all the found occurrences with the new constant.
    /help/img/idea/2017.2/IntroduceConstant_Python_InPlace_ReplaceOccurrences.png
  5. Specify the name of the constant. Select the name from the list or type the name in the box with a red border.
    /help/img/idea/2017.2/IntroduceConstant_Python_InPlace_SelectName.png
  6. To complete the refactoring, press Tab orEnter.

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

Extracting a constant using the dialog box

To extract a constant using the dialog box

If the Enable in-place refactorings check box is cleared on the Editor settings, the Extract Constant refactoring is performed by means of the Introduce Constant Dialog dialog box.

/help/img/idea/2017.2/enableInplaceRefactoringCleared.png

  1. In the Introduce Constant Dialog dialog that opens, specify the name of the new constant.
  2. To automatically replace all occurrences of the selected expression (if it is found more than once),select the option Replace all occurrences.
  3. Click OK to create the constant.
Last modified: 26 October 2017

See Also