PyCharm 2023.2 Help

Extract field

The Extract Field refactoring lets you declare a new field and initialize it with the selected expression. The original expression is replaced with the usage of the field.

Extract a field in place

  1. Place the caret within a piece of code you want to extract into a field.

  2. Press Control+Alt+F or go to Refactor | Extract Field.

  3. Select an expression you want to introduce as a field.

    Select an expression
    If PyCharm detects more than one occurrence in your code, it lets you specify which occurrences to replace.

    Extract multiple occurrences of a field

  4. If relevant, specify where the new field will be initialized - in the current method, or in a class constructor.

  5. Specify the name of the field. Select the name from the list or type the name in the box with a red border.

    Select the name

    To complete the refactoring, press Tab or Enter.

Example

import math class SolverEquation: def demo(self): a = 3 b = 25 c = 46 root1 = (-b + math.sqrt(b**2 - 4*a*c)) / (2*a) root2 = (-b - math.sqrt(b**2 - 4*a*c)) / (2*a) print(root1, root2)
import math class SolverEquation: def demo(self): a = 3 b = 25 c = 46 self.math_sqrt = math.sqrt(b ** 2 - 4 * a * c) root1 = (-b + self.math_sqrt) / (2 * a) root2 = (-b - self.math_sqrt) / (2 * a) print(root1, root2)
Last modified: 07 September 2023