Skip to content

Extract Function to Scope

BetterPy's Extract Function to Scope refactoring moves selected Python code into a named helper and replaces the selection with a call. The helper and call are applied as one undoable change.

MCP tools

analyze_extract_function_to_scope accepts a project file path and one-based selection lines and columns. It reports whether extraction is supported, a conflict code when it is not, inferred inputs and outputs, available destination IDs, and a modification stamp. It does not edit the file.

extract_function_to_scope takes the same selection, a destination ID from analysis, and the new function name. It applies the refactoring without a dialog and returns the updated file text. Pass the analysis modification stamp as expectedModificationStamp to reject an edit if the file changed between calls. Both tools are available only when this feature is included in the build and enabled in BetterPy settings.

Supported destinations

  • Current function inserts a local helper before the selected code.
  • An enclosing function inserts the helper into a containing function that can access the values needed at the call site.
  • Class inserts a @staticmethod helper into the class that directly contains the selected method. The option is available in instance, class, and static methods, including methods of nested or function-local classes. Calls use __class__ to refer to the class where the method was defined; self or cls is passed as an ordinary input when the selected code uses it. Nested functions inside a method do not get a class destination.
  • Module creates a module-level helper.

Direct executable statements and expressions at module level can also be selected. Only the module destination is available; selections inside a module-level if, loop, or other compound suite are rejected. The helper is inserted after the module docstring and any from __future__ imports. When extracting code from a function, the module helper is placed before the file-level construct containing that function. Module globals stay live and are resolved when the helper runs. Every selected module binding that must remain visible after extraction is returned to the module.

For module selections, a read-only use of a global after a selected call keeps that live lookup. A read-modify-write of the same global is rejected when a statically resolved call in the selection can mutate it. In the original code, the read happens after the call; passing the global as a helper input would evaluate it before the helper starts and could use a stale value. Same-file wrapper calls and lambda aliases are followed when they can be resolved.

Inputs are passed as helper parameters. Values assigned by the selection and used afterward are returned and assigned at the call site. For example, extracting the assignment below to the module as make_result preserves result for the following return:

def calculate(value):
    result = value + 1
    return result
def make_result(value):
    result = value + 1
    return result


def calculate(value):
    result = make_result(value)
    return result

Safety boundaries

Unsupported selections and destination conflicts leave the file unchanged and do not record an applied refactoring. Extraction is rejected when a selection is partial, crosses executable scopes, or appears in a function header or decorator. Function and module docstrings cannot be selected. Module-level imports, function or class definitions, and annotated assignments cannot be moved into helpers. Import, global/nonlocal, and assignment-expression bindings are rejected when moving them would change which scope owns the name.

Selections with a return, break, or continue that would escape the new helper are rejected. Module outputs assigned only inside a branch or loop are rejected because the helper could not return a value on every path. Zero-argument super() is rejected for every destination. Async-generator delegation is unsupported; supported await and whole-statement synchronous generator selections preserve their async or generator behavior.

Extraction is rejected when selected writes are read by an existing closure or callback invoked within the selection, including callbacks reached through statically resolved same-file wrappers or lambda aliases. Moving those writes into a helper would hide them from the original binding until the helper returns. Augmented assignments count as writes for this check.

Moving code that contains a class-mangled private name outside its original class scope is rejected. A helper name beginning with __ is also rejected when Python would mangle its definition and call differently. Local helpers that stay in the same class scope remain available.

Class extraction is rejected when the containing method declares global or nonlocal __class__, when staticmethod is shadowed in a scope used by the class body, or when the class or a resolved base class explicitly declares a metaclass= argument. Class helper names conflict with direct or inherited runtime member names, including names Python creates through private-name mangling, and with known __slots__ entries. A dynamic __slots__ declaration that cannot be read as a literal also blocks the class destination. Class-name shadowing inside the method and same-named overrides in subclasses are safe because calls are qualified through __class__.

Python normalizes identifiers using NFKC. Helper-name validation and collision checks use that normalized spelling, so visually distinct spellings that Python treats as the same identifier conflict before editing.

Cross-file extraction is not supported. The existing Extract Function and Top-level Extract Function actions remain independent and are unchanged when this feature is disabled.