Skip to content

Targets

Targets are objects representing code elements you can inspect or modify.

Base Classes

Target

The abstract base class for all targets.

class Target(ABC):
    def exists(self) -> bool: ...
    def get_content(self) -> Result: ...

ErrorTarget

Returned when navigation fails. Allows safe chaining.

# Navigation returns ErrorTarget instead of raising
method = rj.file("x.py").find_class("Missing").find_method("foo")
print(type(method))  # ErrorTarget

# Operations return ErrorResult
result = method.rename("bar")
print(result.success)  # False

TargetList

A list of targets supporting batch operations.

classes = rj.find_classes(pattern="^Test")  # TargetList[ClassTarget]

# Filtering
classes.filter(lambda c: c.has_docstring())
classes.in_file("models.py")
classes.matching("User")

# Batch operations
classes.add_decorator("@slow")  # Returns BatchResult
classes.delete()

Python Targets

FileTarget

A Python file.

file = rj.file("models.py")

# Properties
file.path           # Path object
file.exists()       # True if file exists

# Navigation
file.find_class("User")       # ClassTarget
file.find_function("main")    # FunctionTarget
file.find_classes()           # TargetList[ClassTarget]
file.find_functions()         # TargetList[FunctionTarget]
file.line(42)                 # LineTarget
file.lines(10, 20)            # LineBlockTarget
file.block_at_line(15)        # CodeBlockTarget

# Operations
file.add_import("from typing import Optional")
file.add_function("main", body="pass")
file.add_class("Config", body="DEBUG = True")
file.organize_imports()
file.remove_unused_imports()

ModuleTarget

A Python module by dotted path.

module = rj.module("myapp.models")

# Properties
module.module_path   # "myapp.models"
module.file_path     # Resolved Path or None

# Navigation
module.find_class("User")
module.find_function("helper")

# Operations
module.add_function("new_func")
module.add_class("NewClass")

PackageTarget

A Python package directory.

pkg = rj.package("myapp/")

# Properties
pkg.path         # Path to directory
pkg.exists()     # True if __init__.py exists

# Navigation
pkg.get_modules()              # list[Path] of module files
pkg.find_module("models")      # FileTarget for a named module
pkg.find_subpackage("api")     # PackageTarget for a subpackage
pkg.find_classes()             # TargetList[ClassTarget]
pkg.find_functions()           # TargetList[FunctionTarget]

# Operations
pkg.generate_stubs("stubs/")   # Generate .pyi files
pkg.merge_modules(["a.py", "b.py"], into="combined.py")

ClassTarget

A class definition.

cls = file.find_class("User")

# Properties
cls.name                      # "User"
cls.file_path                 # Path to containing file
cls.exists()                  # True if found
cls.has_docstring()           # True if has docstring
cls.get_content()             # Result with source code

# Navigation
cls.find_method("save")       # MethodTarget
cls.find_methods()            # TargetList[MethodTarget]

# Operations
cls.rename("NewName")
cls.add_method("validate", body="return True")
cls.add_attribute("name", type_hint="str", default="''")
cls.add_decorator("dataclass")
cls.remove_decorator("old_decorator")
cls.add_base_class("BaseModel")
cls.remove_base_class("OldBase")
cls.delete()
cls.duplicate("UserCopy")

# Conversions
cls.convert_to_dataclass()
cls.generate_all_dunders()

FunctionTarget

A module-level function.

func = file.find_function("process")

# Properties
func.name                     # "process"
func.file_path                # Path to file
func.exists()                 # True if found
func.has_docstring()          # True if has docstring
func.get_content()            # Result with source code

# Operations
func.rename("process_data")
func.add_decorator("lru_cache")
func.remove_decorator("deprecated")
func.insert_statement("log('start')", position="start")
func.add_parameter("timeout", type_annotation="int", default_value="30")
func.remove_parameter("old_param")
func.set_return_type("list[str]")
func.set_parameter_type("data", "dict[str, Any]")
func.generate_docstring(style="google")
func.delete()

# Conversions
func.convert_to_async()
func.convert_to_sync()

MethodTarget

A method within a class.

method = cls.find_method("save")

# Properties (same as FunctionTarget)
method.name
method.class_name             # Name of containing class
method.file_path
method.exists()
method.has_docstring()

# Operations (same as FunctionTarget)
method.rename("save_data")
method.add_decorator("transaction")
method.insert_statement("self.validate()")
method.set_return_type("bool")
method.delete()

# Additional
method.extract_to_function("save_helper")

LineTarget

A single line in a file.

line = file.line(42)

# Properties
line.line_number              # 42
line.file_path                # Path to file
line.exists()                 # True if line exists
line.get_content()            # Result with line content

# Directive operations
line.add_type_ignore("arg-type")
line.remove_type_ignore()
line.add_noqa("E501")
line.remove_noqa()
line.add_pylint_disable("line-too-long")
line.add_fmt_skip()
line.add_no_cover()

LineBlockTarget

A range of lines.

block = file.lines(10, 20)

# Properties
block.start_line              # 10
block.end_line                # 20
block.file_path               # Path to file
block.get_content()           # Result with content

# Operations
block.move_to(100)                      # Move to line 100
block.move_to_file("other.py", 5)       # (file_path, line_number)
block.rewrite("new content")
block.insert_before("# Start\n")
block.insert_after("# End\n")
block.replace("old", "new")             # Regex replace within the block
block.delete()
block.indent(2)
block.dedent()

# Wrapping
block.wrap_with_fmt_off()
block.wrap_with_pylint_disable(["C0114"])
block.wrap_with_no_cover()

CodeBlockTarget

A detected code structure (class, function, if, for, etc.).

block = file.block_at_line(42)

# Properties
block.kind                    # "class", "function", "if", "for", etc.
block.name                    # Name if applicable
block.start_line              # First line
block.end_line                # Last line
block.file_path               # Path to file

# Operations
block.delete()
block.to_line_block()         # Convert to LineBlockTarget

CommentTarget

A Python comment (standalone or inline).

# Properties
comment.line_number           # Line number
comment.text                  # Comment text (without #)
comment.name                  # Alias for text (used by filtering)
comment.file_path             # Path to file
comment.exists()              # True if the comment still exists

# Operations
comment.get_content()         # Result with the raw comment (incl. #)
comment.rewrite("New comment text")
comment.delete()

# Type checks (properties, not methods)
comment.is_todo               # True for TODO comments
comment.is_fixme              # True for FIXME comments
comment.is_hack               # True for HACK comments
comment.is_xxx                # True for XXX comments
comment.is_type_ignore        # True for "type: ignore" comments
comment.is_noqa               # True for noqa comments

StringLiteralTarget

A string literal in Python code.

# Properties
s.value                       # String content (decoded, without quotes)
s.raw_content                 # Raw source text (with quotes)
s.name                        # Alias for value (used by filtering)
s.line_number                 # Start line
s.file_path                   # Path to file
s.is_docstring                # True if it's a docstring
s.is_multiline                # True for triple-quoted
s.is_fstring                  # True for f-strings
s.is_raw_string               # True for raw (r"...") strings
s.exists()                    # True if the string still exists

# Operations
s.get_content()               # Result with the string value
s.rewrite("new content")      # Replace content (keeps quotes)
s.rewrite(new_content="...")  # Alias for API consistency
s.delete()

# Analysis helpers (properties)
s.looks_like_sql              # True if looks like SQL
s.looks_like_url              # True if contains a URL
s.looks_like_path            # True if looks like a file path
s.looks_like_regex            # True if looks like a regex

Config Targets

TomlTarget

A TOML file.

toml = rj.toml("pyproject.toml")

toml.exists()                 # True if file exists
toml.get("tool.black.line-length")
toml.get("missing.key", default=None)
toml.set("project.version", "2.0.0")
toml.delete("tool.old-tool")
toml.get_section("tool.black")
toml.rewrite(new_content)     # Replace entire file content (validates TOML)

YamlTarget

A YAML file.

yaml = rj.yaml("config.yml")

yaml.exists()
yaml.get("database.host")
yaml.set("database.port", 5432)
yaml.delete("deprecated")

JsonTarget

A JSON file.

json = rj.json("package.json")

json.exists()
json.get("version")
json.set("scripts.test", "pytest")
json.delete("devDependencies.old")

IniTarget

An INI/CFG file.

ini = rj.ini("setup.cfg")

ini.exists()
ini.get("metadata", "name")
ini.set("metadata", "version", "2.0.0")
ini.delete_key("options", "old_option")
ini.add_section("tool:pytest")
ini.get_data()                # Get entire file as nested dict

TextFileTarget

Any text file.

text = rj.text_file("README.md")

text.exists()
text.get_content()
text.get_line(1)              # First line (str or None)
text.line_count()            # Number of lines
text.find_lines(r"## .*")    # Find matching (line_number, text) pairs
text.replace(r"v\d+", "v2")  # Regex replace across the file
text.append("...")
text.prepend("...")
text.insert_at_line(5, "...")
text.delete_line(3)
text.delete_lines(10, 20)
text.rewrite("...")

targets

Unified Target architecture for code refactoring operations.

This package provides a consistent interface for manipulating Python code, configuration files, and text files through Target objects.

Core Classes

Result: Success result from operations ErrorResult: Failure result from operations (never raises) BatchResult: Aggregate result for batch operations Target: Base class for all targets ErrorTarget: Sentinel for failed lookups (allows chaining) TargetList: Batch operations on multiple targets

Python Targets

FileTarget: Individual .py files ModuleTarget: Python modules by dotted path ClassTarget: Class definitions FunctionTarget: Module-level functions MethodTarget: Class methods LineTarget: Single lines LineBlockTarget: Line ranges CodeBlockTarget: Code structures (if, for, while, etc.) CommentTarget: Python comments StringLiteralTarget: String literals

Config Targets

TomlTarget: TOML files JsonTarget: JSON files YamlTarget: YAML files IniTarget: INI/CFG files

Text Targets

TextFileTarget: Any text file TextBlock: Raw text pattern-based manipulation TextMatch: Individual pattern match within a file

BatchResult(results=list()) dataclass

Aggregate result for operations applied to multiple targets.

Used by TargetList when performing batch operations.

all_failed property

True if all operations failed.

diff property

Combined diff from all results.

diffs property

Merged diffs from all results.

failed property

Results that failed.

files_changed property

All files changed across all operations.

partial_success property

True if at least one operation succeeded.

succeeded property

Results that succeeded.

success property

True if all operations succeeded.

get_diff(path=None)

Get diff for a specific file or combined diff.

Parameters

path : Path | None If provided, returns diff for that specific file. If None, returns the combined diff.

Returns

str | None The diff string, or None if no diff available.

ClassTarget(rejig, name, file_path=None)

Bases: Target

Target for a Python class definition.

Provides operations for modifying class attributes, methods, decorators, and more.

Parameters

rejig : Rejig The parent Rejig instance. name : str Name of the class. file_path : Path | None Optional path to the file containing the class. If not provided, the class will be searched across all files.

Examples

cls = rj.file("models.py").find_class("User") cls.add_attribute("email", "str", '""') cls.find_method("save").insert_statement("self.validate()")

end_line property

Ending line number of this class definition (1-indexed).

file_path property

Path to the file containing this class.

has_docstring property

Check if this class has a docstring.

Returns

bool True if the class has a docstring.

Examples

if not cls.has_docstring: ... cls.generate_docstring()

line_number property

Line number where the class is defined (alias for start_line).

start_line property

Starting line number of this class definition (1-indexed).

add_attribute(name, type_hint, default='None')

Add a class-level attribute with type annotation.

Parameters

name : str Name of the attribute to add. type_hint : str Type annotation for the attribute. default : str Default value for the attribute (default: "None").

Returns

Result Result of the operation.

Examples

cls.add_attribute("count", "int", "0") cls.add_attribute("cache", "dict[str, Any] | None", "None")

add_base_class(base_class, position='last')

Add a base class to this class.

Parameters

base_class : str Name of the base class to add. position : str Where to add: "first" or "last". Default "last".

Returns

Result Result of the operation.

Examples

cls.add_base_class("BaseModel") cls.add_base_class("ABC", position="first")

add_decorator(decorator)

Add a decorator to this class.

Parameters

decorator : str Decorator to add (without @ prefix). Can include arguments, e.g., "dataclass(frozen=True)".

Returns

Result Result of the operation.

add_method(name, body='pass', **kwargs)

Add a method to this class.

Parameters

name : str Name of the method to add. body : str Body of the method (default: "pass"). **kwargs Additional options: - params: Parameter list after self (string) - return_type: Return type annotation - decorators: Decorators (list of strings without @)

Returns

Result Result of the operation.

add_mixin(mixin_class)

Add a mixin class to this class.

Mixins are added at the beginning of the base class list following Python MRO conventions.

Parameters

mixin_class : str Name of the mixin class to add.

Returns

Result Result of the operation.

Examples

cls.add_mixin("LoggingMixin")

add_no_cover()

Add pragma: no cover to exclude this class from coverage.

Adds the pragma comment to the class definition line.

Returns

Result Result of the operation.

Examples

cls.add_no_cover()

add_property(prop_name, getter, setter=None, return_type=None)

Add a property to this class.

Parameters

prop_name : str Name of the property. getter : str Body of the getter (return statement or expression). setter : str | None Body of the setter. If None, property is read-only. return_type : str | None Return type annotation for the getter.

Returns

Result Result of the operation.

Examples

cls.add_property("full_name", "f'{self.first} {self.last}'", return_type="str") cls.add_property("age", "self._age", "self._age = value", "int")

add_pylint_disable(codes)

Add pylint: disable comment to this class's definition line.

Parameters

codes : str | list[str] Pylint error codes to disable.

Returns

Result Result of the operation.

Examples

cls.add_pylint_disable("R0903") # too-few-public-methods cls.add_pylint_disable(["R0903", "R0901"])

add_type_hints_from_defaults(overwrite=False)

Add type hints to methods based on parameter defaults.

Infers type hints from: - Default parameter values (e.g., = 0 → int) - Parameter names (e.g., count → int, is_valid → bool)

This primarily targets the init method to infer instance attribute types from default values.

Parameters

overwrite : bool If True, overwrite existing type hints. Default False.

Returns

Result Result of the operation.

Examples

cls.add_type_hints_from_defaults() cls.add_type_hints_from_defaults(overwrite=True)

convert_attribute_to_property(attr_name, getter=True, setter=True)

Convert a class attribute to a property with getter/setter.

Parameters

attr_name : str Name of the attribute to convert. getter : bool If True, generate a getter property. Default True. setter : bool If True, generate a setter. Default True.

Returns

Result Result of the operation.

Examples

cls.convert_attribute_to_property("_name") cls.convert_attribute_to_property("value", setter=False)

convert_from_dataclass(generate_repr=True, generate_eq=True, generate_hash=False)

Convert this dataclass back to a regular class.

Removes @dataclass decorator and generates explicit dunder methods.

Parameters

generate_repr : bool If True, generate repr method. Default True. generate_eq : bool If True, generate eq method. Default True. generate_hash : bool If True, generate hash method. Default False.

Returns

Result Result of the operation.

convert_to_context_manager(enter_body=None, exit_body=None)

Convert this class to a context manager by adding enter/exit.

If the class has open/connect methods, uses them in enter. If the class has close/disconnect methods, uses them in exit. Otherwise, returns self in enter and passes in exit.

Parameters

enter_body : str | None Custom body for enter method. If None, auto-generates. exit_body : str | None Custom body for exit method. If None, auto-generates.

Returns

Result Result of the operation.

Examples

cls.convert_to_context_manager() cls.convert_to_context_manager( ... enter_body="self._conn = self.connect()\nreturn self._conn", ... exit_body="self._conn.close()" ... )

convert_to_dataclass(frozen=False, slots=False)

Convert this class to a dataclass.

Adds @dataclass decorator and converts instance attributes to class-level annotated attributes. Removes init if it only does attribute assignment.

Parameters

frozen : bool If True, add frozen=True to decorator. Default False. slots : bool If True, add slots=True (Python 3.10+). Default False.

Returns

Result Result of the operation.

Examples

cls.convert_to_dataclass() cls.convert_to_dataclass(frozen=True, slots=True)

convert_to_named_tuple()

Convert this class to a NamedTuple.

Returns

Result Result of the operation.

Examples

cls.convert_to_named_tuple()

convert_to_typed_dict(total=True)

Convert this class to a TypedDict.

Parameters

total : bool If True, all keys are required. Default True.

Returns

Result Result of the operation.

Examples

cls.convert_to_typed_dict() cls.convert_to_typed_dict(total=False)

delete()

Delete this class from the file.

Returns

Result Result of the operation.

duplicate(new_name)

Duplicate this class with a new name.

Creates a copy of the class definition with the specified new name. The duplicate is inserted immediately after the original class.

Parameters

new_name : str Name for the duplicated class.

Returns

Result Result of the operation.

Examples

result = cls.duplicate("UserV2") if result.success: ... new_cls = rj.find_class("UserV2")

exists()

Check if this class exists.

extract_abstract_base(abc_name=None, methods=None)

Extract an Abstract Base Class from this class.

Creates a new ABC with abstract method signatures and makes this class inherit from it.

Parameters

abc_name : str | None Name for the new ABC. Defaults to "Base{ClassName}". methods : list[str] | None Method names to make abstract. If None, uses all public methods.

Returns

Result Result of the operation.

Examples

cls.extract_abstract_base() cls.extract_abstract_base("AbstractUser", methods=["save", "validate"])

extract_protocol(protocol_name, methods=None)

Extract a Protocol from this class.

Creates a new Protocol class with specified method signatures and inserts it before the original class.

Parameters

protocol_name : str Name for the new Protocol class. methods : list[str] | None Method names to include. If None, includes all public methods.

Returns

Result Result of the operation.

Examples

cls.extract_protocol("UserProtocol") cls.extract_protocol("ValidatorProtocol", methods=["validate", "check"])

find_method(name)

Find a method within this class.

Parameters

name : str Name of the method to find.

Returns

MethodTarget | ErrorTarget MethodTarget if found, ErrorTarget otherwise.

find_methods(pattern=None)

Find all methods in this class, optionally filtered by pattern.

Parameters

pattern : str | None Optional regex pattern to filter method names.

Returns

TargetList[MethodTarget] List of matching MethodTarget objects.

find_methods_without_docstrings()

Find all methods in this class that don't have docstrings.

Returns

TargetList[MethodTarget] List of methods without docstrings.

Examples

missing = cls.find_methods_without_docstrings() for method in missing: ... method.generate_docstring()

generate_all_dunders(overwrite=False)

Generate all common dunder methods (init, repr, eq, hash).

Parameters

overwrite : bool If True, replace existing dunders. Default False.

Returns

Result Result of the operation.

Examples

cls.generate_all_dunders()

generate_docstrings(style='google', overwrite=False)

Generate docstrings for all methods in this class.

Parameters

style : str Docstring style: "google", "numpy", or "sphinx". Defaults to "google". overwrite : bool Whether to overwrite existing docstrings. Default False.

Returns

Result Result of the operation.

Examples

cls.generate_docstrings() cls.generate_docstrings(style="numpy")

generate_eq(overwrite=False)

Generate eq method from class attributes.

Parameters

overwrite : bool If True, replace existing eq. Default False.

Returns

Result Result of the operation.

generate_hash(overwrite=False)

Generate hash method from class attributes.

Parameters

overwrite : bool If True, replace existing hash. Default False.

Returns

Result Result of the operation.

generate_init(overwrite=False)

Generate init method from class attributes.

Parameters

overwrite : bool If True, replace existing init. Default False.

Returns

Result Result of the operation.

Examples

cls.generate_init() cls.generate_init(overwrite=True)

generate_repr(overwrite=False)

Generate repr method from class attributes.

Parameters

overwrite : bool If True, replace existing repr. Default False.

Returns

Result Result of the operation.

generate_test_file(output_path, include_setup=True, include_teardown=False)

Generate a complete test file for this class.

Creates a pytest test file with test stubs for all public methods.

Parameters

output_path : str | Path Path where the test file should be written. include_setup : bool Whether to include a setup_method. Default True. include_teardown : bool Whether to include a teardown_method. Default False.

Returns

Result Result of the operation.

Examples

cls.generate_test_file("tests/test_calculator.py") cls.generate_test_file("tests/test_user.py", include_teardown=True)

generate_test_stub(test_dir=None)

Generate a test stub in the default location.

Creates a test file in the tests/ directory mirroring the source structure.

Parameters

test_dir : str | Path | None Base directory for tests. Defaults to "tests" in project root.

Returns

Result Result of the operation.

Examples

cls.generate_test_stub() # Creates tests/test_mymodule.py cls.generate_test_stub("test_suite/unit")

get_content()

Get the source code of this class.

Returns

Result Result with class source code in data field if successful.

get_docstring()

Get the docstring of this class.

Returns

Result Result with docstring text in data field if successful. Returns empty string if no docstring exists.

Examples

result = cls.get_docstring() if result.success and result.data: ... print(result.data)

get_source()

Get just the class signature (without body).

Returns

Result Result with class signature in data field if successful. The signature includes decorators, class name, and base classes.

Examples

sig = cls.get_source() if sig.success: ... print(sig.data) # "class MyClass(BaseClass):"

move_to(destination)

Move this class to a different module using rope.

Parameters

destination : str | Target Destination module path (e.g., 'myapp.models').

Returns

Result Result of the operation.

remove_attribute(attr_name)

Remove a class-level attribute.

Parameters

attr_name : str Name of the attribute to remove.

Returns

Result Result of the operation.

remove_base_class(base_class)

Remove a base class from this class.

Parameters

base_class : str Name of the base class to remove.

Returns

Result Result of the operation.

Examples

cls.remove_base_class("OldBase")

remove_decorator(decorator)

Remove a decorator from this class.

Parameters

decorator : str Decorator to remove (without @ prefix).

Returns

Result Result of the operation.

remove_object_base()

Remove unnecessary (object) base class from this class.

In Python 3, all classes implicitly inherit from object, so explicitly inheriting from object is unnecessary.

Returns

Result Result of the operation.

Examples

cls.remove_object_base() # class Foo(object): → class Foo:

rename(new_name, update_references=True)

Rename this class.

When update_references is True (default), uses rope to rename the class and every reference across the project. When False, or when rope is unavailable, only the class definition is rewritten via libcst.

Parameters

new_name : str New name for the class. update_references : bool If True, also update references to the class throughout the project.

Returns

Result Result of the operation.

CodeBlockTarget(rejig, file_path, kind, start_line, end_line, name=None)

Bases: Target

Target for a detected code structure (class, function, if-block, etc.).

This target represents a syntactic code block that can be manipulated as a unit. It can be converted to a LineBlockTarget for line-based operations.

Parameters

rejig : Rejig The parent Rejig instance. file_path : Path Path to the file containing the code block. kind : CodeBlockKind Type of code block (class, function, if, for, etc.). start_line : int 1-based starting line number. end_line : int 1-based ending line number. name : str | None Name of the block (for named blocks like classes/functions).

Examples

block = rj.file("utils.py").find_block_at_line(42) block.to_line_block().indent()

file_path property

Path to the file containing this code block.

dedent(levels=1)

Dedent (unindent) this code block.

Parameters

levels : int Number of indentation levels to remove.

Returns

Result Result of the operation.

delete()

Delete this code block from the file.

Returns

Result Result of the operation.

exists()

Check if this code block still exists.

find_at_line(rejig, file_path, line_number) classmethod

Find the code block containing a specific line.

Parameters

rejig : Rejig The Rejig instance. file_path : Path Path to the file. line_number : int 1-based line number to search for.

Returns

CodeBlockTarget | None The innermost code block containing the line, or None if not found.

get_content()

Get the content of this code block.

Returns

Result Result with block content in data field if successful.

indent(levels=1)

Indent this code block.

Parameters

levels : int Number of indentation levels to add.

Returns

Result Result of the operation.

insert_after(content)

Insert content after this code block.

Parameters

content : str Content to insert.

Returns

Result Result of the operation.

insert_before(content)

Insert content before this code block.

Parameters

content : str Content to insert.

Returns

Result Result of the operation.

move_to(destination)

Move this code block to a different location in the same file.

Parameters

destination : int | Target Target line number to move to.

Returns

Result Result of the operation.

move_to_file(file_path, line_number)

Move this code block to a different file.

Parameters

file_path : str | Path Path to the destination file. line_number : int 1-based line number to insert at in the destination file.

Returns

Result Result of the operation.

Examples

block = rj.file("source.py").block_at_line(10) block.move_to_file("destination.py", 5)

replace(pattern, replacement)

Replace pattern in this code block.

Parameters

pattern : str Regex pattern to search for. replacement : str Replacement string.

Returns

Result Result of the operation.

rewrite(new_content)

Replace the content of this code block.

Parameters

new_content : str New content for the block.

Returns

Result Result of the operation.

to_line_block()

Convert this code block to a LineBlockTarget.

Returns

LineBlockTarget A LineBlockTarget covering the same lines.

CommentTarget(rejig, file_path, line_number, content)

Bases: Target

Target for a Python comment.

Provides operations for reading, modifying, and deleting comments in Python source files.

Parameters

rejig : Rejig The parent Rejig instance. file_path : Path Path to the file containing the comment. line_number : int 1-based line number where the comment is located. content : str The comment content (including # prefix).

Examples

comments = rj.file("utils.py").find_comments(pattern="TODO") for comment in comments: ... print(f"{comment.line_number}: {comment.text}")

file_path property

Path to the file containing this comment.

is_fixme property

Check if this is a FIXME comment.

is_hack property

Check if this is a HACK comment.

is_noqa property

Check if this is a noqa comment.

is_todo property

Check if this is a TODO comment.

is_type_ignore property

Check if this is a type: ignore comment.

is_xxx property

Check if this is an XXX comment.

name property

Alias for text, used by TargetList filtering.

text property

The comment text without the # prefix.

delete()

Delete this comment from the file.

If the comment is on a line by itself, the entire line is removed. If it's an inline comment, only the comment portion is removed.

Returns

Result Result of the operation.

exists()

Check if this comment still exists at the recorded location.

get_content()

Get the content of this comment.

Returns

Result Result with comment content in data field if successful.

rewrite(new_content)

Replace the comment with new content.

Parameters

new_content : str New comment content (with or without # prefix).

Returns

Result Result of the operation.

ErrorResult(success, message, files_changed=list(), data=None, diff=None, diffs=dict(), exception=None, operation='', target_repr='') dataclass

Bases: Result

Result for failed operations - never raises automatically.

Attributes:

Name Type Description
exception Exception | None

The original exception, if any

operation str

Name of the attempted operation

target_repr str

String representation of the target

raise_if_error()

Explicitly re-raise the exception if the programmer wants to.

ErrorTarget(rejig, error_message)

Bases: Target

A target that represents a failed lookup - all operations return ErrorResult.

Navigation methods return ErrorTarget (not ErrorResult) to allow chaining. Operation methods return ErrorResult.

This allows code like

rj.module("nonexistent").find_class("Foo").add_method("bar")

to return an ErrorResult without raising, even though the module doesn't exist.

__getattr__(name)

Any other method call returns an ErrorResult.

FileTarget(rejig, path)

Bases: Target

Target for a specific Python file.

Provides operations for reading, modifying, and navigating within a Python source file.

Parameters

rejig : Rejig The parent Rejig instance. path : str | Path Path to the Python file.

Examples

file = rj.file("mymodule.py") file.add_class("NewClass", body="pass") file.find_class("MyClass").add_method("process")

file_path property

The path to this file (alias for consistency with other targets).

add_class(name, body='pass', **kwargs)

Add a class to this file.

Parameters

name : str Name of the class to add. body : str Body of the class (default: "pass"). **kwargs Additional options: - bases: Base classes (comma-separated string) - decorators: Decorators (list of strings without @)

Returns

Result Result of the operation.

Add a copyright header to this file.

copyright_text : str Copyright holder text (e.g., "MyCompany Inc."). year : int | None Copyright year. Defaults to current year.

Result Result of the operation.

file = rj.file("mymodule.py") file.add_copyright_header("Copyright 2024 MyCompany")

add_function(name, body='pass', **kwargs)

Add a module-level function to this file.

Parameters

name : str Name of the function to add. body : str Body of the function (default: "pass"). **kwargs Additional options: - params: Parameter list (string) - return_type: Return type annotation - decorators: Decorators (list of strings without @)

Returns

Result Result of the operation.

add_future_annotations()

Add from __future__ import annotations to this file.

This enables PEP 563 postponed evaluation of annotations, allowing forward references and reducing runtime overhead.

Returns

Result Result of the operation.

Examples

file = rj.file("mymodule.py") file.add_future_annotations()

add_import(import_statement, sort=None)

Add an import statement to this file.

The statement is inserted after the last existing import; the file's imports are then re-sorted and grouped with isort unless sorting is disabled (see sort). Sorting fixes the insertion point, so the added import lands in its correct group regardless of where it was placed textually.

Parameters

import_statement : str Import statement to add (without newline). sort : bool | None Whether to re-sort imports afterwards. None (default) follows the parent Rejig(auto_sort_imports=...) setting; True or False overrides it for this call. See :meth:sort_imports.

Returns

Result Result of the operation.

add_license_header(license_name, copyright_holder=None, year=None)

Add a license header to this file.

Parameters

license_name : str License identifier: "MIT", "Apache-2.0", "GPL-3.0", "BSD-3-Clause", or "Proprietary". copyright_holder : str | None Copyright holder name. If None, uses a placeholder. year : int | None Copyright year. Defaults to current year.

Returns

Result Result of the operation.

Examples

file = rj.file("mymodule.py") file.add_license_header("MIT") file.add_license_header("Apache-2.0", "MyCompany Inc.")

add_missing_imports(import_mapping=None)

Add imports for undefined names in this file.

Note: This is a heuristic operation. It detects names that appear to be undefined (not imported or defined locally) and adds imports for them if a mapping is provided.

Parameters

import_mapping : dict[str, str] | None Mapping of name to import statement. For example: {"Optional": "from typing import Optional"} If None, uses a default mapping for common names.

Returns

Result Result with the list of potentially missing imports in data.

Examples

file = rj.file("mymodule.py") result = file.add_missing_imports({ ... "Optional": "from typing import Optional", ... "Path": "from pathlib import Path", ... })

add_pytest_fixture(fixture_name, body, scope='function', autouse=False, params=None)

Add a pytest fixture to this file.

Typically used with conftest.py files to add shared fixtures.

Parameters

fixture_name : str Name of the fixture function. body : str Body of the fixture function. scope : str Fixture scope: "function", "class", "module", or "session". Defaults to "function". autouse : bool If True, fixture is automatically used. Default False. params : list[str] | None Optional list of fixture parameters for parametrized fixtures.

Returns

Result Result of the operation.

Examples

conftest = rj.file("tests/conftest.py") conftest.add_pytest_fixture( ... "db_session", ... scope="function", ... body="yield get_db()" ... )

add_to_all(name)

Add a name to all.

Parameters

name : str Name to add to all.

Returns

Result Result of the operation.

Examples

init_file = rj.file("mypackage/init.py") init_file.add_to_all("new_function")

block_at_line(line_number)

Get the code block containing the given line.

Finds the innermost code structure (class, function, if, for, while, try, with) that contains the specified line.

Parameters

line_number : int 1-based line number.

Returns

CodeBlockTarget | ErrorTarget CodeBlockTarget if a block is found, ErrorTarget otherwise.

Examples

block = rj.file("utils.py").block_at_line(42) print(block.kind) # "class", "function", "if", etc. block.delete() # Delete the entire block

convert_absolute_to_relative()

Convert all absolute imports to relative imports where possible.

Only converts imports that are within the same package.

Returns

Result Result of the operation.

Examples

file = rj.file("myapp/utils.py") file.convert_absolute_to_relative()

convert_docstring_style(from_style, to_style)

Convert all docstrings from one style to another.

Parameters

from_style : str | None Source docstring style ("google", "numpy", "sphinx"), or None to auto-detect. to_style : str Target docstring style ("google", "numpy", "sphinx").

Returns

Result Result of the operation.

Examples

file = rj.file("mymodule.py") file.convert_docstring_style("sphinx", "google") file.convert_docstring_style(None, "numpy") # auto-detect source

convert_format_strings_to_fstrings()

Convert .format() string formatting to f-strings.

Converts

"Hello {}".format(name) → f"Hello {name}" "Hello {0}".format(name) → f"Hello {name}" "Hello {name}".format(name=value) → f"Hello {value}"

Returns

Result Result of the operation.

Examples

file = rj.file("legacy_module.py") file.convert_format_strings_to_fstrings()

convert_percent_format_to_fstrings()

Convert % string formatting to f-strings.

Converts

"Hello %s" % name → f"Hello {name}" "Hello %s %s" % (a, b) → f"Hello {a} {b}" "%(name)s" % {"name": value} → f"{value}"

Returns

Result Result of the operation.

Examples

file = rj.file("legacy_module.py") file.convert_percent_format_to_fstrings()

convert_relative_to_absolute(package_name=None)

Convert all relative imports to absolute imports.

Parameters

package_name : str | None The package name to use as the base for absolute imports. If None, attempts to detect from project configuration.

Returns

Result Result of the operation.

Examples

file = rj.file("myapp/utils.py") file.convert_relative_to_absolute("myapp")

convert_to_package(keep_original=False)

Convert this file to a package directory.

Transforms utils.py into utils/init.py.

Parameters

keep_original : bool Whether to keep the original file. Default False.

Returns

Result Result of the operation.

Examples

file = rj.file("utils.py") file.convert_to_package() # Creates utils/init.py

convert_type_comments_to_annotations()

Convert type comments to inline annotations.

Converts

x = 1 # type: int

To: x: int = 1

And

def f(x): # type: (int) -> str

To: def f(x: int) -> str:

Returns

Result Result of the operation.

Examples

file = rj.file("legacy_module.py") file.convert_type_comments_to_annotations()

delete()

Delete this file.

Returns

Result Result of the operation.

exists()

Check if this file exists.

find_class(name)

Find a class by name in this file.

Parameters

name : str Name of the class to find.

Returns

ClassTarget | ErrorTarget ClassTarget if found, ErrorTarget otherwise.

find_classes(pattern=None)

Find all classes in this file, optionally filtered by pattern.

Parameters

pattern : str | None Optional regex pattern to filter class names.

Returns

TargetList[ClassTarget] List of matching ClassTarget objects.

find_directives()

Find all linting directives in this file.

Returns

DirectiveTargetList List of DirectiveTarget objects.

Examples

file = rj.file("mymodule.py") directives = file.find_directives() for d in directives: ... print(f"Line {d.line_number}: {d.directive_type}")

find_function(name)

Find a module-level function by name in this file.

Parameters

name : str Name of the function to find.

Returns

FunctionTarget | ErrorTarget FunctionTarget if found, ErrorTarget otherwise.

find_functions(pattern=None)

Find all module-level functions in this file.

Parameters

pattern : str | None Optional regex pattern to filter function names.

Returns

TargetList[FunctionTarget] List of matching FunctionTarget objects.

find_imports()

Find all imports in this file.

Returns

ImportTargetList List of ImportTarget objects for all imports in this file.

Examples

file = rj.file("mymodule.py") imports = file.find_imports() for imp in imports: ... print(f"Line {imp.line_number}: {imp.import_info.import_statement}")

find_missing_docstrings()

Find all functions, methods, and classes without docstrings.

Returns

TargetList[Target] List of FunctionTarget, MethodTarget, and ClassTarget objects that don't have docstrings.

Examples

file = rj.file("mymodule.py") missing = file.find_missing_docstrings() print(f"Found {len(missing)} items without docstrings")

find_noqa_comments()

Find all noqa comments in this file.

Returns

TargetList[LineTarget] List of LineTarget objects for lines with noqa comments.

Examples

file = rj.file("mymodule.py") noqa = file.find_noqa_comments() print(f"Found {len(noqa)} noqa comments")

find_outdated_docstrings()

Find functions/methods with outdated docstrings.

A docstring is considered outdated if: - It documents parameters that no longer exist in the signature - It's missing documentation for parameters in the signature

Returns

Result Result with list of outdated docstrings in data field. Each entry is a dict with: - name: function/method name - class_name: class name (or None for functions) - stale_params: params documented but not in signature - missing_params: params in signature but not documented

Examples

file = rj.file("mymodule.py") result = file.find_outdated_docstrings() for item in result.data: ... print(f"{item['name']}: stale={item['stale_params']}, missing={item['missing_params']}")

find_type_ignores()

Find all type: ignore comments in this file.

Returns

TargetList[LineTarget] List of LineTarget objects for lines with type: ignore.

Examples

file = rj.file("mymodule.py") ignores = file.find_type_ignores() print(f"Found {len(ignores)} type: ignore comments")

find_unused_imports()

Find all unused imports in this file.

Returns

ImportTargetList List of ImportTarget objects for unused imports.

Examples

file = rj.file("mymodule.py") unused = file.find_unused_imports() print(f"Found {len(unused)} unused imports") unused.delete() # Remove all unused imports

generate_all_docstrings(style='google', overwrite=False)

Generate docstrings for all functions and methods without them.

Parameters

style : str Docstring style: "google", "numpy", or "sphinx". Defaults to "google". overwrite : bool Whether to overwrite existing docstrings. Default False.

Returns

Result Result of the operation.

Examples

file = rj.file("mymodule.py") file.generate_all_docstrings() file.generate_all_docstrings(style="numpy", overwrite=True)

generate_all_exports(include_private=False)

Generate all from all public definitions in this file.

Creates an all list containing all public classes, functions, and module-level variables.

Parameters

include_private : bool Whether to include private names (starting with _).

Returns

Result Result with generated all in data field.

Examples

init_file = rj.file("mypackage/init.py") init_file.generate_all_exports()

get_all_exports()

Get the current all exports from this file.

Returns

list[str] List of exported names, or empty list if no all.

Examples

file = rj.file("mypackage/init.py") exports = file.get_all_exports() print(exports) # ['Class1', 'function1', ...]

get_content()

Get the content of this file.

Returns

Result Result with file content in data field if successful.

has_header()

Check if this file has a copyright/license header.

Returns

bool True if the file has a header.

Examples

file = rj.file("mymodule.py") if not file.has_header(): ... file.add_license_header("MIT")

line(line_number)

Get a specific line of this file.

Parameters

line_number : int 1-based line number.

Returns

LineTarget Target for the specified line.

lines(start, end)

Get a range of lines from this file.

Parameters

start : int 1-based starting line number. end : int 1-based ending line number (inclusive).

Returns

LineBlockTarget Target for the specified line range.

modernize_all()

Apply all modernization transformations to this file.

This is a convenience method that applies: 1. F-string conversion (format and percent) 2. Type hint modernization 3. Python 2 compatibility removal 4. Deprecated code replacement

Returns

Result Result of the operation with summary of changes.

Examples

file = rj.file("legacy_module.py") file.modernize_all()

modernize_type_hints()

Modernize type hints to Python 3.10+ syntax.

Converts: - List[str] → list[str] - Dict[str, int] → dict[str, int] - Optional[str] → str | None - Union[str, int] → str | int

Returns

Result Result of the operation.

Examples

file = rj.file("mymodule.py") file.modernize_type_hints()

organize_imports(first_party_packages=None)

Organize imports in this file (isort-like).

Groups imports into: 1. future imports 2. Standard library imports 3. Third-party imports 4. Local/first-party imports

Within each group, imports are sorted alphabetically.

Parameters

first_party_packages : set[str] | None Set of package names to treat as first-party. If None, will try to auto-detect from the project root.

Returns

Result Result of the operation.

Examples

file = rj.file("mymodule.py") file.organize_imports()

remove_all_directives()

Remove all linting directive comments from this file.

Removes all: type: ignore, noqa, pylint: disable, fmt: skip/off/on, pragma: no cover.

Returns

Result Result of the operation.

Examples

file = rj.file("mymodule.py") file.remove_all_directives()

remove_all_noqa()

Remove all noqa comments from this file.

Returns

Result Result of the operation.

Examples

file = rj.file("mymodule.py") file.remove_all_noqa()

remove_all_type_ignores()

Remove all type: ignore comments from this file.

Returns

Result Result of the operation.

Examples

file = rj.file("mymodule.py") file.remove_all_type_ignores()

remove_from_all(name)

Remove a name from all.

Parameters

name : str Name to remove from all.

Returns

Result Result of the operation.

Examples

init_file = rj.file("mypackage/init.py") init_file.remove_from_all("old_function")

remove_python2_compatibility()

Remove Python 2 compatibility code from this file.

Removes: - future imports (except annotations) - super(ClassName, self) → super() - u"string" prefixes - Unnecessary (object) base class

Returns

Result Result of the operation.

Examples

file = rj.file("legacy_module.py") file.remove_python2_compatibility()

remove_six_usage()

Remove six library compatibility usage.

Converts: - six.text_type → str - six.binary_type → bytes - six.PY2 → False, six.PY3 → True - six.moves.range → range

Returns

Result Result of the operation.

Examples

file = rj.file("legacy_module.py") file.remove_six_usage()

remove_unused_imports(sort=None)

Remove all unused imports from this file.

After removing imports, the remaining imports are re-sorted and grouped with isort unless sorting is disabled (see sort).

Parameters

sort : bool | None Whether to re-sort imports afterwards. None (default) follows the parent Rejig(auto_sort_imports=...) setting; True or False overrides it for this call. See :meth:sort_imports.

Returns

Result Result of the operation, including count of removed imports.

Examples

file = rj.file("mymodule.py") result = file.remove_unused_imports() print(result.message)

replace(pattern, replacement, count=0)

Replace literal text in this file, in place.

pattern is matched literally (plain str.replace), so regex metacharacters such as ( or . stand for themselves. For regular expressions and backreferences, use :meth:replace_pattern.

Because :meth:TargetList.replace_all dispatches to this method, a whole-tree literal find-and-replace is a one-liner::

rj.find_files("app/*/api.py").replace_all("foo(", "bar(")
Parameters

pattern : str Literal text to search for. replacement : str Replacement text. count : int Maximum number of replacements (0 = all).

Returns

Result Result of the operation; a no-op success when nothing matched.

replace_deprecated_code(replacements=None)

Replace deprecated API usage with modern equivalents.

Replaces common deprecated patterns like: - collections.MutableMapping → collections.abc.MutableMapping - assertEquals → assertEqual - logger.warn → logger.warning

Parameters

replacements : dict[str, str] | None Custom replacement mapping. If None, uses built-in defaults.

Returns

Result Result of the operation.

Examples

file = rj.file("tests.py") file.replace_deprecated_code() file.replace_deprecated_code({"oldFunc": "newFunc"})

replace_pattern(pattern, replacement, count=0, flags=0)

Replace occurrences of a regex pattern in this file.

Operates on raw text — use the CST-based methods (find_function, find_class, etc.) when you need to respect Python structure.

Parameters

pattern : str Regular expression pattern to replace. replacement : str Replacement string (may include backreferences like \1). count : int Maximum replacements (0 = unlimited). flags : int Regex flags.

Returns

Result Result of the operation. Success with "No matches found" message when the pattern doesn't match anything.

rewrite(new_content)

Replace the entire content of this file.

Parameters

new_content : str New content for the file.

Returns

Result Result of the operation.

sort_imports()

Sort and group this file's imports with isort.

isort is configured from the project's own settings, discovered by searching upward from the file for the nearest pyproject.toml / setup.cfg / .isort.cfg. The result therefore matches what the project's own isort / pre-commit / CI run would produce, including project-specific options such as force_single_line, known_third_party and src_paths.

This is the manual counterpart to the automatic sorting performed by :meth:add_import and :meth:remove_unused_imports.

Returns

Result Result of the operation. Succeeds with a no-op message when the imports are already sorted.

split(by='class', output_dir=None, create_init=True)

Split this file into multiple files.

Parameters

by : str What to split by: "class" or "function". output_dir : Path | None Output directory. Defaults to a package named after the file. create_init : bool Whether to create an init.py with imports.

Returns

Result Result of the operation.

Examples

file = rj.file("big_module.py") file.split(by="class") # One file per class file.split(by="function") # One file per function

update_all_exports(include_private=False)

Update all to sync with actual definitions.

Adds missing exports and removes stale ones.

Parameters

include_private : bool Whether to include private names (starting with _).

Returns

Result Result of the operation.

Examples

init_file = rj.file("mypackage/init.py") init_file.update_all_exports()

Update the copyright year in this file's header.

Updates patterns like: - "Copyright 2023" -> "Copyright 2023-2024" - "Copyright 2023-2024" -> "Copyright 2023-2025"

new_year : int | None Target year. Defaults to current year.

Result Result of the operation.

file = rj.file("mymodule.py") file.update_copyright_year()

FunctionTarget(rejig, name, file_path=None)

Bases: Target

Target for a module-level Python function.

Provides operations for modifying function body, decorators, parameters, and more.

Parameters

rejig : Rejig The parent Rejig instance. name : str Name of the function. file_path : Path | None Optional path to the file containing the function. If not provided, the function will be searched across all files.

Examples

func = rj.file("utils.py").find_function("process_data") func.insert_statement("logger.info('Processing started')") func.add_decorator("timing")

end_line property

Ending line number of this function definition (1-indexed).

file_path property

Path to the file containing this function.

has_docstring property

Check if this function has a docstring.

Returns

bool True if the function has a docstring.

Examples

if not func.has_docstring: ... func.generate_docstring()

line_number property

Line number where the function is defined (alias for start_line).

start_line property

Starting line number of this function definition (1-indexed).

add_caching_decorator(ttl=None)

Add a caching decorator to this function.

Parameters

ttl : int | None Time-to-live in seconds. If None, uses lru_cache without maxsize.

Returns

Result Result of the operation.

Examples

func.add_caching_decorator() func.add_caching_decorator(ttl=300)

add_decorator(decorator)

Add a decorator to this function.

Parameters

decorator : str Decorator to add (without @ prefix). Can include arguments, e.g., "lru_cache(maxsize=128)".

Returns

Result Result of the operation.

add_docstring_example(example)

Add an example to the docstring.

Parameters

example : str Example code (can include >>> and output).

Returns

Result Result of the operation.

Examples

func.add_docstring_example(">>> process(5)\n10")

add_docstring_raises(exception, description)

Add a raises entry to the docstring.

Parameters

exception : str Name of the exception (e.g., "ValueError"). description : str Description of when the exception is raised.

Returns

Result Result of the operation.

Examples

func.add_docstring_raises("ValueError", "If input is negative")

add_docstring_returns(description)

Add or update the returns section in the docstring.

Parameters

description : str Description of the return value.

Returns

Result Result of the operation.

Examples

func.add_docstring_returns("The processed result")

add_logging(level='debug', include_args=False, logger_name='logger')

Add logging statement at the start of this function.

Parameters

level : str Logging level: "debug", "info", "warning", "error", "critical". Defaults to "debug". include_args : bool If True, include argument values in the log message. Defaults to False. logger_name : str Name of the logger variable. Defaults to "logger".

Returns

Result Result of the operation.

Examples

func.add_logging(level="debug", include_args=True)

add_no_cover()

Add pragma: no cover to exclude this function from coverage.

Adds the pragma comment to the function definition line.

Returns

Result Result of the operation.

Examples

func.add_no_cover()

add_parameter(param_name, type_annotation=None, default_value=None, position='end')

Add a parameter to the function signature.

Parameters

param_name : str Name of the parameter to add. type_annotation : str | None Type annotation for the parameter. default_value : str | None Default value for the parameter. position : str Where to add: "start", "end". Defaults to "end".

Returns

Result Result of the operation.

Examples

func.add_parameter("timeout", "int", "30") func.add_parameter("verbose", "bool", "False")

add_pylint_disable(codes)

Add pylint: disable comment to this function's definition line.

Parameters

codes : str | list[str] Pylint error codes to disable.

Returns

Result Result of the operation.

Examples

func.add_pylint_disable("C0114") func.add_pylint_disable(["C0114", "C0115"])

add_retry_decorator(max_attempts=3, exceptions=None)

Add a retry decorator to this function.

Parameters

max_attempts : int Maximum number of retry attempts. Defaults to 3. exceptions : list[str] | None List of exception types to catch for retry. Defaults to ["Exception"].

Returns

Result Result of the operation.

Examples

func.add_retry_decorator(max_attempts=3, exceptions=["ConnectionError"])

add_timing_decorator()

Add a timing decorator to this function.

Returns

Result Result of the operation.

Examples

func.add_timing_decorator()

convert_to_async()

Convert this function to async.

Adds the async keyword to the function definition.

Returns

Result Result of the operation.

Examples

func.convert_to_async()

convert_to_sync()

Convert this function from async to sync.

Removes the async keyword and all await expressions.

Returns

Result Result of the operation.

Examples

func.convert_to_sync()

delete()

Delete this function from the file.

Returns

Result Result of the operation.

exists()

Check if this function exists.

generate_docstring(style='google', summary='', overwrite=False)

Generate a docstring for this function.

Creates a docstring from the function signature including parameters, return type, and raised exceptions.

Parameters

style : str Docstring style: "google", "numpy", or "sphinx". Defaults to "google". summary : str Custom summary line. If empty, auto-generates from function name. overwrite : bool Whether to overwrite existing docstring. Default False.

Returns

Result Result of the operation.

Examples

func.generate_docstring() func.generate_docstring(style="numpy") func.generate_docstring(summary="Process the input data.")

generate_test_stub(test_dir=None)

Generate a test stub for this function.

Creates a pytest test function stub in the test directory.

Parameters

test_dir : str | Path | None Base directory for tests. Defaults to "tests" in project root.

Returns

Result Result of the operation.

Examples

func.generate_test_stub() # Creates tests/test_mymodule.py func.generate_test_stub("test_suite/unit")

generate_tests_from_doctest(output_path=None)

Convert doctest examples in this function to pytest tests.

Extracts doctest examples from the function's docstring and generates equivalent pytest test functions.

Parameters

output_path : str | Path | None Where to write the tests. If None, writes to tests/test_{module}.py.

Returns

Result Result of the operation.

Examples

func.generate_tests_from_doctest() func.generate_tests_from_doctest("tests/test_doctests.py")

get_content()

Get the source code of this function.

Returns

Result Result with function source code in data field if successful.

get_docstring()

Get the docstring of this function.

Returns

Result Result with docstring text in data field if successful. Returns empty string if no docstring exists.

Examples

result = func.get_docstring() if result.success and result.data: ... print(result.data)

infer_type_hints(overwrite=False)

Infer and add type hints based on defaults and name heuristics.

Uses heuristics to infer types from: - Default parameter values (e.g., = 0 → int) - Parameter names (e.g., count → int, is_valid → bool)

Parameters

overwrite : bool If True, overwrite existing type hints. Default False.

Returns

Result Result of the operation.

Examples

func.infer_type_hints() func.infer_type_hints(overwrite=True)

insert_after_match(pattern, code)

Insert code after a line matching a regex pattern.

Parameters

pattern : str Regex pattern to match against line content. code : str Code to insert after the matching line.

Returns

Result Result of the operation.

insert_before_match(pattern, code)

Insert code before a line matching a regex pattern.

Parameters

pattern : str Regex pattern to match against line content. code : str Code to insert before the matching line.

Returns

Result Result of the operation.

insert_statement(statement, position='start')

Insert a statement into the function body.

Parameters

statement : str Python statement to insert. position : str Where to insert: "start" (after docstring) or "end". Defaults to "start".

Returns

Result Result of the operation.

Examples

func.insert_statement("logger.info('Starting')") func.insert_statement("return result", position="end")

move_to(destination)

Move this function to a different module using rope.

Parameters

destination : str | Target Destination module path (e.g., 'utils.helpers').

Returns

Result Result of the operation.

remove_decorator(decorator)

Remove a decorator from this function.

Parameters

decorator : str Decorator to remove (without @ prefix).

Returns

Result Result of the operation.

remove_parameter(param_name)

Remove a parameter from the function signature.

Parameters

param_name : str Name of the parameter to remove.

Returns

Result Result of the operation.

Examples

func.remove_parameter("deprecated_arg")

remove_type_hints()

Remove all type hints from this function.

Removes return type annotations and parameter type annotations.

Returns

Result Result of the operation.

Examples

func.remove_type_hints()

rename(new_name, update_callers=True)

Rename this function.

When update_callers is True (default), uses rope to rename the definition and every caller across the project. When False, or when rope is unavailable, only the def line is rewritten via regex.

Parameters

new_name : str New name for the function. update_callers : bool If True, also update calls to the function throughout the project.

Returns

Result Result of the operation.

rename_parameter(old_name, new_name)

Rename a parameter in the function signature.

Also updates all references to the parameter within the function body.

Parameters

old_name : str Current name of the parameter. new_name : str New name for the parameter.

Returns

Result Result of the operation.

Examples

func.rename_parameter("old_arg", "new_arg")

reorder_parameters(param_order)

Reorder parameters in the function signature.

Parameters not in the order list are appended at the end in their original relative order.

Parameters

param_order : list[str] Ordered list of parameter names defining the new order.

Returns

Result Result of the operation.

Examples

func.reorder_parameters(["required", "optional", "extra"])

replace_body(new_body)

Replace the body of this function.

Preserves the existing signature, decorators, and docstring (when the docstring is the first statement and new_body does not start with one).

Parameters

new_body : str New function body as a Python source string. Should NOT be indented; indentation is handled automatically.

Returns

Result Result of the operation.

Examples

func.replace_body("return value * 2") func.replace_body("if x:\n return x\nreturn 0")

replace_match(pattern, code)

Replace a line matching a regex pattern with new code.

Parameters

pattern : str Regex pattern to match against line content. code : str Code to replace the matching line with.

Returns

Result Result of the operation.

set_parameter_type(param_name, param_type)

Set the type annotation for a parameter.

Parameters

param_name : str Name of the parameter to annotate. param_type : str The type annotation (e.g., "dict[str, Any]").

Returns

Result Result of the operation.

Examples

func.set_parameter_type("data", "dict[str, Any]") func.set_parameter_type("timeout", "int")

set_return_type(return_type)

Set the return type annotation for this function.

Parameters

return_type : str The return type annotation (e.g., "list[str]", "None").

Returns

Result Result of the operation.

Examples

func.set_return_type("list[str]") func.set_return_type("dict[str, Any]")

set_signature(params=None, return_type=None)

Replace the parameter list and/or return type of this function.

Pass params="" to clear all parameters. Pass return_type="" to remove an existing return annotation.

Parameters

params : str | None New parameter list as a Python source string (e.g. "x: int, y: int = 0"). None leaves the existing parameter list untouched. return_type : str | None New return type as a Python source string (e.g. "bool"). None leaves the existing return annotation untouched; "" removes it.

Returns

Result Result of the operation.

Examples

func.set_signature(params="token: str, timeout: int = 60") func.set_signature(return_type="bool") func.set_signature(return_type="") # drop annotation

update_docstring_param(param_name, description)

Update or add a parameter description in the docstring.

Parameters

param_name : str Name of the parameter to document. description : str Description of the parameter.

Returns

Result Result of the operation.

Examples

func.update_docstring_param("timeout", "Maximum wait time in seconds")

wrap_with_try_except(exceptions, handler)

Wrap the function body with a try/except block.

Parameters

exceptions : list[str] List of exception types to catch. handler : str Handler code to execute in the except block. Use 'e' to reference the caught exception. Separate multiple statements with semicolons.

Returns

Result Result of the operation.

Examples

func.wrap_with_try_except( ... ["ValueError", "TypeError"], ... "logger.error(f'Error: {e}'); raise" ... )

IniTarget(rejig, path)

Bases: Target

Target for an INI or CFG configuration file.

Provides operations for reading, modifying, and querying INI/CFG files using Python's configparser.

Parameters

rejig : Rejig The parent Rejig instance. path : str | Path Path to the INI/CFG file.

Examples

ini = rj.ini("setup.cfg") ini.get("metadata", "name") ini.set("metadata", "version", "1.0.0")

file_path property

Path to the INI file.

add_section(section)

Add a new section.

Parameters

section : str Section name to add.

Returns

Result Result of the operation.

delete_key(section, key)

Delete a key from a section.

Parameters

section : str Section name. key : str Key to delete.

Returns

Result Result of the operation.

delete_section(section)

Delete an entire section.

Parameters

section : str Section name to delete.

Returns

Result Result of the operation.

exists()

Check if this INI file exists.

get(section, key, default=None)

Get a value from a section.

Parameters

section : str Section name. key : str Key name within the section. default : str | None Default value if key not found.

Returns

str | None The value, or default if not found.

Examples

ini.get("metadata", "name") "my-project" ini.get("metadata", "license", "MIT")

get_bool(section, key, default=False)

Get a boolean value from a section.

Parameters

section : str Section name. key : str Key name within the section. default : bool Default value if key not found.

Returns

bool The boolean value.

get_content()

Get the raw content of the INI file.

Returns

Result Result with file content in data field if successful.

get_data()

Get the parsed INI data as a nested dictionary.

Returns

Result Result with parsed dict in data field if successful. The dict has section names as keys and section data dicts as values.

Examples

result = ini.get_data() if result.success: ... for section, values in result.data.items(): ... print(f"[{section}]")

get_float(section, key, default=0.0)

Get a float value from a section.

Parameters

section : str Section name. key : str Key name within the section. default : float Default value if key not found.

Returns

float The float value.

get_int(section, key, default=0)

Get an integer value from a section.

Parameters

section : str Section name. key : str Key name within the section. default : int Default value if key not found.

Returns

int The integer value.

get_section(section)

Get all key-value pairs in a section.

Parameters

section : str Section name.

Returns

dict[str, str] Dictionary of key-value pairs.

has_key(section, key)

Check if a key exists in a section.

Parameters

section : str Section name. key : str Key name.

Returns

bool True if key exists.

has_section(section)

Check if a section exists.

Parameters

section : str Section name to check.

Returns

bool True if section exists.

keys(section)

Get all keys in a section.

Parameters

section : str Section name.

Returns

list[str] List of keys in the section.

rewrite(new_content)

Replace the entire content of the INI file.

Parameters

new_content : str New INI content.

Returns

Result Result of the operation.

sections()

Get all section names.

Returns

list[str] List of section names.

set(section, key, value)

Set a value in a section.

Parameters

section : str Section name. key : str Key name within the section. value : str Value to set.

Returns

Result Result of the operation.

Examples

ini.set("metadata", "version", "2.0.0")

set_section(section, data)

Set all key-value pairs in a section.

Parameters

section : str Section name. data : dict[str, str] Key-value pairs to set.

Returns

Result Result of the operation.

JsonTarget(rejig, path)

Bases: Target

Target for a JSON configuration file.

Provides operations for reading, modifying, and querying JSON files.

Parameters

rejig : Rejig The parent Rejig instance. path : str | Path Path to the JSON file.

Examples

json_file = rj.json("package.json") json_file.get("name") json_file.set("version", "1.0.0")

file_path property

Path to the JSON file.

add_script(name, command)

Add a script (for package.json).

delete(key_path)

Delete a key by key path.

Parameters

key_path : str | Sequence[str] Path to the key to delete: a dotted string, a list of literal segments, or a :class:KeyPath built with /.

Returns

Result Result of the operation.

exists()

Check if this JSON file exists.

get(key_path, default=None)

Get a value by key path.

Parameters

key_path : str | Sequence[str] Path to the key: a dotted string ("scripts.build", "dependencies.react"), a list of literal segments (["dependencies", "react"]), or a :class:KeyPath built with / (KeyPath("dependencies") / "react" — use this when a key contains a literal .). default : Any Default value if key not found.

Returns

Any The value at the key path, or default if not found.

Examples

json_file.get("name") "my-project" json_file.get("scripts.test", "npm test")

get_content()

Get the raw content of the JSON file.

Returns

Result Result with file content in data field if successful.

get_data()

Get the parsed JSON data.

Returns

Result Result with parsed data in data field if successful.

get_package_name()

Get the package name (for package.json).

get_package_version()

Get the package version (for package.json).

get_scripts()

Get scripts (for package.json).

has_key(key_path)

Check if a key exists.

Parameters

key_path : str Dotted path to check.

Returns

bool True if the key exists.

keys(section_path=None)

Get keys at a section path.

Parameters

section_path : str | None Dotted path to section, or None for root keys.

Returns

list[str] List of keys at the section.

rewrite(new_content)

Replace the entire content of the JSON file.

Parameters

new_content : str New JSON content.

Returns

Result Result of the operation.

set(key_path, value)

Set a value by key path.

Parameters

key_path : str | Sequence[str] Path to the key: a dotted string ("version", "scripts.build"), a list of literal segments, or a :class:KeyPath built with /. value : Any Value to set.

Returns

Result Result of the operation.

set_package_version(version)

Set the package version (for package.json).

KeyPath(*parts)

Bases: Sequence

A composable, pathlib-style key path for config targets.

Build a path by joining segments with /. Each operand is one literal key segment, so a segment may itself contain . (or any other character) and is never split apart:

KeyPath("security") / "ignore-vulnerabilities" / "SFTY-2026.0616" KeyPath('security', 'ignore-vulnerabilities', 'SFTY-2026.0616')

Pass the result anywhere a key path is accepted (get / set / delete on TOML/YAML/JSON targets). This is the unambiguous alternative to the dotted-string form for keys that themselves contain dots::

cfg.set(KeyPath("security") / "ignore" / "CVE-2026.0001", "reviewed")

It is a :class:collections.abc.Sequence of its segments, so it can also be indexed, iterated and measured with len().

parts property

The path's literal segments.

LineBlockTarget(rejig, file_path, start_line, end_line)

Bases: Target

Target for a contiguous range of lines in a Python file.

Provides operations for reading, modifying, moving, and transforming blocks of code by line numbers.

Parameters

rejig : Rejig The parent Rejig instance. file_path : Path Path to the file containing the lines. start_line : int 1-based starting line number. end_line : int 1-based ending line number (inclusive).

Examples

block = rj.file("utils.py").lines(10, 20) block.indent() block.delete()

file_path property

Path to the file containing this block.

dedent(levels=1, spaces_per_level=4)

Dedent (unindent) this line block.

Parameters

levels : int Number of indentation levels to remove (default: 1). spaces_per_level : int Number of spaces per indentation level (default: 4).

Returns

Result Result of the operation.

delete()

Delete this line block from the file.

Returns

Result Result of the operation.

exists()

Check if this line range exists in the file.

get_content()

Get the content of this line block.

Returns

Result Result with block content in data field if successful.

indent(levels=1, spaces_per_level=4)

Indent this line block.

Parameters

levels : int Number of indentation levels to add (default: 1). spaces_per_level : int Number of spaces per indentation level (default: 4).

Returns

Result Result of the operation.

insert_after(content)

Insert content after this line block.

Parameters

content : str Content to insert.

Returns

Result Result of the operation.

insert_before(content)

Insert content before this line block.

Parameters

content : str Content to insert.

Returns

Result Result of the operation.

move_to(destination)

Move this line block to a different location in the same file.

Parameters

destination : int | Target Target line number or LineTarget to move after.

Returns

Result Result of the operation.

move_to_file(file_path, line_number)

Move this line block to a different file.

Parameters

file_path : str | Path Path to the destination file. line_number : int 1-based line number to insert at in the destination file.

Returns

Result Result of the operation.

Examples

block = rj.file("source.py").lines(10, 20) block.move_to_file("destination.py", 5)

replace(pattern, replacement)

Replace pattern in this line block.

Parameters

pattern : str Regex pattern to search for. replacement : str Replacement string.

Returns

Result Result of the operation.

rewrite(new_content)

Replace the content of this line block.

Parameters

new_content : str New content for the block.

Returns

Result Result of the operation.

wrap_with_fmt_off()

Wrap this line block with fmt: off/on comments.

Adds: - # fmt: off before the block - # fmt: on after the block

Returns

Result Result of the operation.

Examples

block = rj.file("utils.py").lines(10, 20) block.wrap_with_fmt_off()

wrap_with_no_cover()

Wrap this line block with pragma: no cover comment.

For multi-line blocks, this adds the pragma comment to the first statement line. For better coverage exclusion of blocks, consider using the pragma on the controlling statement (if/for/while/etc.) or wrapping in a function.

Returns

Result Result of the operation.

Examples

block = rj.file("utils.py").lines(10, 20) block.wrap_with_no_cover()

wrap_with_pylint_disable(codes)

Wrap this line block with pylint: disable/enable comments.

Adds: - # pylint: disable=codes before the block - # pylint: enable=codes after the block

Parameters

codes : str | list[str] Pylint error codes to disable (e.g., "line-too-long" or ["C0114", "C0115"]).

Returns

Result Result of the operation.

Examples

block = rj.file("utils.py").lines(10, 20) block.wrap_with_pylint_disable("C0114") block.wrap_with_pylint_disable(["C0114", "C0115"])

LineTarget(rejig, file_path, line_number)

Bases: Target

Target for a single line in a Python file.

Provides operations for reading, modifying, and adding directives to a specific line of code.

Parameters

rejig : Rejig The parent Rejig instance. file_path : Path Path to the file containing the line. line_number : int 1-based line number.

Examples

line = rj.file("utils.py").line(42) line.add_type_ignore("arg-type") line.add_noqa("E501")

file_path property

Path to the file containing this line.

add_fmt_skip()

Add a fmt: skip comment to this line (for black/formatter).

Returns

Result Result of the operation.

add_no_cover()

Add a pragma: no cover comment to this line.

Returns

Result Result of the operation.

add_noqa(codes=None)

Add a noqa comment to this line.

Parameters

codes : str | list[str] | None Specific error codes to suppress (e.g., "E501" or ["E501", "F401"]).

Returns

Result Result of the operation.

add_pylint_disable(codes)

Add a pylint: disable comment to this line.

Parameters

codes : str | list[str] Pylint error codes to disable (e.g., "line-too-long" or ["C0114", "C0115"]).

Returns

Result Result of the operation.

Examples

line.add_pylint_disable("line-too-long") line.add_pylint_disable(["C0114", "C0115"])

add_type_ignore(error_code=None, reason=None)

Add a type: ignore comment to this line.

Parameters

error_code : str | None Specific mypy error code to ignore (e.g., "arg-type"). reason : str | None Optional reason for the ignore.

Returns

Result Result of the operation.

Examples

line.add_type_ignore() # Generic ignore line.add_type_ignore("arg-type") line.add_type_ignore("arg-type", reason="Legacy API")

delete()

Delete this line from the file.

Returns

Result Result of the operation.

exists()

Check if this line exists in the file.

get_content()

Get the content of this line.

Returns

Result Result with line content in data field if successful.

insert_after(content)

Insert content after this line.

Parameters

content : str Content to insert (will be added as a new line).

Returns

Result Result of the operation.

insert_before(content)

Insert content before this line.

Parameters

content : str Content to insert (will be added as a new line).

Returns

Result Result of the operation.

remove_fmt_skip()

Remove the fmt: skip comment from this line.

Returns

Result Result of the operation.

remove_no_cover()

Remove the pragma: no cover comment from this line.

Returns

Result Result of the operation.

remove_noqa()

Remove the noqa comment from this line.

Returns

Result Result of the operation.

remove_pylint_disable()

Remove the pylint: disable comment from this line.

Returns

Result Result of the operation.

remove_type_ignore()

Remove the type: ignore comment from this line.

Returns

Result Result of the operation.

rewrite(new_content)

Replace the content of this line.

Parameters

new_content : str New content for the line.

Returns

Result Result of the operation.

MethodTarget(rejig, class_name, name, file_path=None)

Bases: Target

Target for a method within a Python class.

Provides operations for modifying method body, decorators, parameters, and more.

Parameters

rejig : Rejig The parent Rejig instance. class_name : str Name of the class containing the method. name : str Name of the method. file_path : Path | None Optional path to the file containing the class.

Examples

method = rj.file("models.py").find_class("User").find_method("save") method.insert_statement("self.validate()") method.add_decorator("transaction.atomic")

end_line property

Ending line number of this method definition (1-indexed).

file_path property

Path to the file containing this method.

has_docstring property

Check if this method has a docstring.

Returns

bool True if the method has a docstring.

Examples

if not method.has_docstring: ... method.generate_docstring()

line_number property

Line number where the method is defined (alias for start_line).

start_line property

Starting line number of this method definition (1-indexed).

add_caching_decorator(ttl=None)

Add a caching decorator to this method.

Parameters

ttl : int | None Time-to-live in seconds. If None, uses lru_cache without maxsize.

Returns

Result Result of the operation.

Examples

method.add_caching_decorator() method.add_caching_decorator(ttl=300)

add_decorator(decorator)

Add a decorator to this method.

Parameters

decorator : str Decorator to add (without @ prefix).

Returns

Result Result of the operation.

add_docstring_example(example)

Add an example to the docstring.

Parameters

example : str Example code (can include >>> and output).

Returns

Result Result of the operation.

Examples

method.add_docstring_example(">>> obj.save()\n'saved'")

add_docstring_raises(exception, description)

Add a raises entry to the docstring.

Parameters

exception : str Name of the exception (e.g., "ValueError"). description : str Description of when the exception is raised.

Returns

Result Result of the operation.

Examples

method.add_docstring_raises("ValueError", "If input is negative")

add_docstring_returns(description)

Add or update the returns section in the docstring.

Parameters

description : str Description of the return value.

Returns

Result Result of the operation.

Examples

method.add_docstring_returns("The saved instance")

add_logging(level='debug', include_args=False, logger_name='logger')

Add logging statement at the start of this method.

Parameters

level : str Logging level: "debug", "info", "warning", "error", "critical". Defaults to "debug". include_args : bool If True, include argument values in the log message. Defaults to False. logger_name : str Name of the logger variable. Defaults to "logger".

Returns

Result Result of the operation.

Examples

method.add_logging(level="debug", include_args=True)

add_no_cover()

Add pragma: no cover to exclude this method from coverage.

Adds the pragma comment to the method definition line.

Returns

Result Result of the operation.

Examples

method.add_no_cover()

add_parameter(param_name, type_annotation=None, default_value=None, position='end')

Add a parameter to the method signature.

Parameters

param_name : str Name of the parameter to add. type_annotation : str | None Type annotation for the parameter. default_value : str | None Default value for the parameter. position : str Where to add: "start" (after self/cls), "end". Defaults to "end".

Returns

Result Result of the operation.

add_pylint_disable(codes)

Add pylint: disable comment to this method's definition line.

Parameters

codes : str | list[str] Pylint error codes to disable.

Returns

Result Result of the operation.

Examples

method.add_pylint_disable("C0116") # missing-function-docstring method.add_pylint_disable(["C0116", "R0201"])

add_retry_decorator(max_attempts=3, exceptions=None)

Add a retry decorator to this method.

Parameters

max_attempts : int Maximum number of retry attempts. Defaults to 3. exceptions : list[str] | None List of exception types to catch for retry. Defaults to ["Exception"].

Returns

Result Result of the operation.

Examples

method.add_retry_decorator(max_attempts=3, exceptions=["ConnectionError"])

add_timing_decorator()

Add a timing decorator to this method.

Returns

Result Result of the operation.

Examples

method.add_timing_decorator()

convert_to_async()

Convert this method to async.

Adds the async keyword to the method definition.

Returns

Result Result of the operation.

Examples

method.convert_to_async()

convert_to_classmethod()

Convert a staticmethod to a classmethod and add cls parameter.

Returns

Result Result of the operation.

convert_to_sync()

Convert this method from async to sync.

Removes the async keyword and all await expressions.

Returns

Result Result of the operation.

Examples

method.convert_to_sync()

delete()

Delete this method from the class.

Returns

Result Result of the operation.

exists()

Check if this method exists.

extract_to_function(name)

Extract this method to a module-level function.

The method is converted to a standalone function, and the method is replaced with a call to that function. The first parameter (self/cls) is preserved.

Parameters

name : str Name for the extracted function.

Returns

Result Result of the operation.

Examples

result = method.extract_to_function("process_user_data") if result.success: ... func = rj.find_function("process_user_data")

generate_docstring(style='google', summary='', overwrite=False)

Generate a docstring for this method.

Creates a docstring from the method signature including parameters, return type, and raised exceptions.

Parameters

style : str Docstring style: "google", "numpy", or "sphinx". Defaults to "google". summary : str Custom summary line. If empty, auto-generates from method name. overwrite : bool Whether to overwrite existing docstring. Default False.

Returns

Result Result of the operation.

Examples

method.generate_docstring() method.generate_docstring(style="numpy") method.generate_docstring(summary="Save the model to disk.")

generate_test(test_cases=None, output_path=None)

Generate a test for this method.

Generates either a simple test stub or a parameterized test if test cases are provided.

Parameters

test_cases : list[dict] | None Optional list of test cases. Each dict should have: - "input": dict of parameter name to value - "expected": expected return value - "description": optional test case description output_path : str | Path | None Where to write the test. Defaults to tests/test_{class}.py.

Returns

Result Result of the operation.

Examples

method.generate_test() method.generate_test( ... test_cases=[ ... {"input": {"data": "valid"}, "expected": True}, ... {"input": {"data": ""}, "expected": False}, ... ] ... )

get_content()

Get the source code of this method.

Returns

Result Result with method source code in data field if successful.

get_docstring()

Get the docstring of this method.

Returns

Result Result with docstring text in data field if successful. Returns empty string if no docstring exists.

Examples

result = method.get_docstring() if result.success and result.data: ... print(result.data)

infer_type_hints(overwrite=False)

Infer and add type hints based on defaults and name heuristics.

Uses heuristics to infer types from: - Default parameter values (e.g., = 0 → int) - Parameter names (e.g., count → int, is_valid → bool)

Parameters

overwrite : bool If True, overwrite existing type hints. Default False.

Returns

Result Result of the operation.

Examples

method.infer_type_hints() method.infer_type_hints(overwrite=True)

insert_after_match(pattern, code)

Insert code after a line matching a regex pattern.

Parameters

pattern : str Regex pattern to match against line content. code : str Code to insert after the matching line.

Returns

Result Result of the operation.

insert_before_match(pattern, code)

Insert code before a line matching a regex pattern.

Parameters

pattern : str Regex pattern to match against line content. code : str Code to insert before the matching line.

Returns

Result Result of the operation.

insert_statement(statement, position='start')

Insert a statement into the method body.

Parameters

statement : str Python statement to insert. position : str Where to insert: "start" (after docstring) or "end". Defaults to "start".

Returns

Result Result of the operation.

Examples

method.insert_statement("self.validate()") method.insert_statement("return result", position="end")

remove_decorator(decorator)

Remove a decorator from this method.

Parameters

decorator : str Decorator to remove (without @ prefix).

Returns

Result Result of the operation.

remove_parameter(param_name)

Remove a parameter from the method signature.

Parameters

param_name : str Name of the parameter to remove.

Returns

Result Result of the operation.

Examples

method.remove_parameter("deprecated_arg")

remove_type_hints()

Remove all type hints from this method.

Removes return type annotations and parameter type annotations.

Returns

Result Result of the operation.

Examples

method.remove_type_hints()

rename(new_name)

Rename this method.

Note: This only renames the method definition. It does not update calls to the method throughout the codebase.

Parameters

new_name : str New name for the method.

Returns

Result Result of the operation.

rename_parameter(old_name, new_name)

Rename a parameter in the method signature.

Also updates all references to the parameter within the method body.

Parameters

old_name : str Current name of the parameter. new_name : str New name for the parameter.

Returns

Result Result of the operation.

Examples

method.rename_parameter("old_arg", "new_arg")

reorder_parameters(param_order)

Reorder parameters in the method signature.

Parameters not in the order list are appended at the end in their original relative order.

Parameters

param_order : list[str] Ordered list of parameter names defining the new order.

Returns

Result Result of the operation.

Examples

method.reorder_parameters(["self", "required", "optional"])

replace_identifier(old_name, new_name)

Replace identifier references within the method.

Parameters

old_name : str Identifier to replace. new_name : str New identifier name (can include dots, e.g., "cls.cache").

Returns

Result Result of the operation.

Examples

method.replace_identifier("cache", "cls._cache")

replace_match(pattern, code)

Replace a line matching a regex pattern with new code.

Parameters

pattern : str Regex pattern to match against line content. code : str Code to replace the matching line with.

Returns

Result Result of the operation.

set_parameter_type(param_name, param_type)

Set the type annotation for a parameter.

Parameters

param_name : str Name of the parameter to annotate. param_type : str The type annotation (e.g., "dict[str, Any]").

Returns

Result Result of the operation.

Examples

method.set_parameter_type("data", "dict[str, Any]") method.set_parameter_type("timeout", "int")

set_return_type(return_type)

Set the return type annotation for this method.

Parameters

return_type : str The return type annotation (e.g., "list[str]", "None").

Returns

Result Result of the operation.

Examples

method.set_return_type("list[str]") method.set_return_type("Result")

update_docstring_param(param_name, description)

Update or add a parameter description in the docstring.

Parameters

param_name : str Name of the parameter to document. description : str Description of the parameter.

Returns

Result Result of the operation.

Examples

method.update_docstring_param("timeout", "Maximum wait time in seconds")

wrap_with_try_except(exceptions, handler)

Wrap the method body with a try/except block.

Parameters

exceptions : list[str] List of exception types to catch. handler : str Handler code to execute in the except block. Use 'e' to reference the caught exception. Separate multiple statements with semicolons.

Returns

Result Result of the operation.

Examples

method.wrap_with_try_except( ... ["ValueError", "TypeError"], ... "logger.error(f'Error: {e}'); raise" ... )

ModuleTarget(rejig, module_path)

Bases: Target

Target for a Python module identified by dotted path.

This target resolves a dotted module path (e.g., 'myapp.models.user') to the corresponding Python file and provides operations on it.

Parameters

rejig : Rejig The parent Rejig instance. module_path : str Dotted module path (e.g., "myapp.models" or "myapp.models.user").

Examples

module = rj.module("myapp.models") module.find_class("User").add_attribute("email", "str") module.add_import("from typing import Optional")

file_path property

Resolved filesystem path for this module.

add_class(name, body='pass', **kwargs)

Add a class to this module.

Parameters

name : str Name of the class to add. body : str Body of the class (default: "pass"). **kwargs Additional options (bases, decorators).

Returns

Result Result of the operation.

add_function(name, body='pass', **kwargs)

Add a module-level function to this module.

Parameters

name : str Name of the function to add. body : str Body of the function (default: "pass"). **kwargs Additional options (params, return_type, decorators).

Returns

Result Result of the operation.

add_import(import_statement)

Add an import statement to this module.

Parameters

import_statement : str Import statement to add (without newline).

Returns

Result Result of the operation.

delete()

Delete this module's file.

Returns

Result Result of the operation.

exists()

Check if this module exists.

find_class(name)

Find a class by name in this module.

Parameters

name : str Name of the class to find.

Returns

ClassTarget | ErrorTarget ClassTarget if found, ErrorTarget otherwise.

find_classes(pattern=None)

Find all classes in this module.

Parameters

pattern : str | None Optional regex pattern to filter class names.

Returns

TargetList[ClassTarget] List of matching ClassTarget objects.

find_function(name)

Find a module-level function by name in this module.

Parameters

name : str Name of the function to find.

Returns

FunctionTarget | ErrorTarget FunctionTarget if found, ErrorTarget otherwise.

find_functions(pattern=None)

Find all module-level functions in this module.

Parameters

pattern : str | None Optional regex pattern to filter function names.

Returns

TargetList[FunctionTarget] List of matching FunctionTarget objects.

get_content()

Get the content of this module's file.

Returns

Result Result with file content in data field if successful.

line(line_number)

Get a specific line of this module.

Parameters

line_number : int 1-based line number.

Returns

LineTarget Target for the specified line.

lines(start, end)

Get a range of lines from this module.

Parameters

start : int 1-based starting line number. end : int 1-based ending line number (inclusive).

Returns

LineBlockTarget Target for the specified line range.

move_to(new_location, update_imports=True)

Move this module to a new location with import updates.

Parameters

new_location : str New module path (e.g., "myapp.core.utils"). update_imports : bool Whether to update imports across the project. Default True.

Returns

Result Result of the operation.

Examples

module = rj.module("myapp.utils") module.move_to("myapp.core.utils") # Moves and updates imports

rename(new_name, update_imports=True)

Rename this module and update imports across the project.

Parameters

new_name : str New module path (e.g., "myapp.new_utils"). update_imports : bool Whether to update imports across the project. Default True.

Returns

Result Result of the operation.

Examples

module = rj.module("myapp.old_utils") module.rename("myapp.new_utils") # Updates imports across project

rewrite(new_content)

Replace the entire content of this module.

Parameters

new_content : str New content for the module.

Returns

Result Result of the operation.

PackageTarget(rejig, path)

Bases: Target

Target for a Python package (directory with init.py).

Provides operations for working with packages including finding modules, classes, and functions within the package.

Parameters

rejig : Rejig The parent Rejig instance. path : str | Path Path to the package directory.

Examples

pkg = rj.package("myapp/models") pkg.find_classes() # Find all classes in the package pkg.init_file.add_import("from .user import User")

file_path property

Path to the package directory.

init_file property

Get the init.py file target.

name property

The package name (directory name).

Add a copyright header to all Python files in this package.

copyright_text : str Copyright holder text (e.g., "MyCompany Inc."). year : int | None Copyright year. Defaults to current year. recursive : bool Whether to include files in subpackages. Default True.

Result Result of the operation.

pkg = rj.package("mypackage/") pkg.add_copyright_header("Copyright 2024 MyCompany")

add_import(import_statement)

Add an import statement to the package's init.py.

Parameters

import_statement : str Import statement to add.

Returns

Result Result of the operation.

add_license_header(license_name, copyright_holder=None, year=None, recursive=True)

Add a license header to all Python files in this package.

Parameters

license_name : str License identifier: "MIT", "Apache-2.0", "GPL-3.0", "BSD-3-Clause", or "Proprietary". copyright_holder : str | None Copyright holder name. If None, uses a placeholder. year : int | None Copyright year. Defaults to current year. recursive : bool Whether to include files in subpackages. Default True.

Returns

Result Result of the operation.

Examples

pkg = rj.package("mypackage/") pkg.add_license_header("MIT", "MyCompany Inc.")

convert_unittest_to_pytest()

Convert unittest test cases to pytest style.

Transforms all test files in this package (recursively) from unittest style to pytest style, converting: - self.assertEqual(a, b) -> assert a == b - self.assertTrue(x) -> assert x - self.assertFalse(x) -> assert not x - self.assertIsNone(x) -> assert x is None - self.assertRaises(X) -> pytest.raises(X) - And many more assertion methods

Returns

Result Result of the operation.

Examples

tests_pkg = rj.package("tests/") tests_pkg.convert_unittest_to_pytest()

create_module(name, content='')

Create a new module in this package.

Parameters

name : str Module name (without .py extension). content : str Initial content for the module.

Returns

Result Result of the operation.

create_subpackage(name, init_content='')

Create a new subpackage in this package.

Parameters

name : str Subpackage name. init_content : str Initial content for init.py.

Returns

Result Result of the operation.

delete()

Delete this package and all its contents.

Returns

Result Result of the operation.

exists()

Check if this package exists (directory with init.py).

find_class(name)

Find a class by name across all modules in this package.

Parameters

name : str Name of the class to find.

Returns

ClassTarget | ErrorTarget ClassTarget if found, ErrorTarget otherwise.

find_classes(pattern=None)

Find all classes in this package.

Parameters

pattern : str | None Optional regex pattern to filter class names.

Returns

TargetList[ClassTarget] List of matching ClassTarget objects.

find_function(name)

Find a module-level function by name across all modules.

Parameters

name : str Name of the function to find.

Returns

FunctionTarget | ErrorTarget FunctionTarget if found, ErrorTarget otherwise.

find_functions(pattern=None)

Find all module-level functions in this package.

Parameters

pattern : str | None Optional regex pattern to filter function names.

Returns

TargetList[FunctionTarget] List of matching FunctionTarget objects.

find_module(name)

Find a module by name within this package.

Parameters

name : str Module name (without .py extension).

Returns

FileTarget | ErrorTarget FileTarget if found, ErrorTarget otherwise.

find_subpackage(name)

Find a subpackage by name.

Parameters

name : str Subpackage name.

Returns

PackageTarget | ErrorTarget PackageTarget if found, ErrorTarget otherwise.

generate_stubs(output=None)

Generate type stub files (.pyi) for all modules in this package.

Creates stub files that contain only function signatures, class definitions, and type annotations. This is useful for providing type hints for libraries or for use with type checkers.

Parameters

output : str | Path | None Output directory for stub files. If None, creates a 'stubs/' directory next to the package.

Returns

Result Result of the operation.

Examples

pkg = rj.package("src/mypackage") pkg.generate_stubs() # Creates stubs/ alongside package pkg.generate_stubs("custom_stubs/") # Use custom directory

generate_test_stubs(test_dir=None)

Generate test stubs for all classes and functions in this package.

Creates test files with stub test functions for all public classes and functions found in the package.

Parameters

test_dir : str | Path | None Base directory for tests. Defaults to "tests" in project root.

Returns

Result Result of the operation.

Examples

pkg = rj.package("src/myapp") pkg.generate_test_stubs() # Creates tests/test_*.py files

get_content()

Get the content of the package's init.py file.

Returns

Result Result with init.py content in data field if successful.

get_modules()

Get all Python modules in this package.

Returns

list[Path] List of paths to Python files in the package (non-recursive).

get_subpackages()

Get all subpackages in this package.

Returns

list[Path] List of paths to subpackage directories.

merge_modules(module_names, into, delete_originals=False, generate_all=True)

Merge multiple modules in this package into one.

Parameters

module_names : list[str] List of module names to merge (without .py extension). into : str Target module name (without .py extension). delete_originals : bool Whether to delete the original files after merging. generate_all : bool Whether to generate an all list.

Returns

Result Result of the operation.

Examples

pkg = rj.package("mypackage/") pkg.merge_modules(["utils_a", "utils_b"], into="utils")

Update the copyright year in all Python files in this package.

Updates patterns like: - "Copyright 2023" -> "Copyright 2023-2024" - "Copyright 2023-2024" -> "Copyright 2023-2025"

new_year : int | None Target year. Defaults to current year. recursive : bool Whether to include files in subpackages. Default True.

Result Result of the operation.

pkg = rj.package("mypackage/") pkg.update_copyright_year()

update_test_imports(old_module, new_module)

Update imports in test files after refactoring.

Useful for updating test imports when source modules are moved or renamed.

Parameters

old_module : str The old module path (e.g., "myapp.utils"). new_module : str The new module path (e.g., "myapp.helpers.utils").

Returns

Result Result of the operation.

Examples

tests_pkg = rj.package("tests/") tests_pkg.update_test_imports("myapp.utils", "myapp.helpers.utils")

Result(success, message, files_changed=list(), data=None, diff=None, diffs=dict()) dataclass

Base result for all operations.

Operations never raise exceptions. Instead, they return Result objects that indicate success or failure.

Attributes:

Name Type Description
success bool

Whether the operation succeeded

message str

Human-readable description of what happened

files_changed list[Path]

List of files that were modified

data Any

Optional payload for operations that return data

diff str | None

Combined unified diff of all changes (if any)

diffs dict[Path, str]

Per-file diffs mapping path to diff string

get_diff(path=None)

Get diff for a specific file or combined diff.

Parameters

path : Path | None If provided, returns diff for that specific file. If None, returns the combined diff.

Returns

str | None The diff string, or None if no diff available.

is_error()

Check if this result represents an error.

StringLiteralTarget(rejig, file_path, line_number, value, raw_content, is_docstring=False)

Bases: Target

Target for a string literal in Python source code.

Provides operations for reading, modifying, and analyzing string literals in Python files. Useful for finding hardcoded strings, SQL queries, or extracting strings for internationalization.

Parameters

rejig : Rejig The parent Rejig instance. file_path : Path Path to the file containing the string. line_number : int 1-based line number where the string starts. value : str The string value (decoded, without quotes). raw_content : str The raw string as it appears in source (with quotes). is_docstring : bool Whether this string is a docstring.

Examples

strings = rj.file("queries.py").find_strings(pattern="SELECT") for s in strings: ... print(f"{s.line_number}: {s.value[:50]}")

file_path property

Path to the file containing this string.

is_fstring property

Check if this is an f-string.

is_multiline property

Check if this is a multiline string (triple-quoted).

is_raw_string property

Check if this is a raw string.

looks_like_path property

Check if this string looks like a file path.

looks_like_regex property

Check if this string looks like a regex pattern.

looks_like_sql property

Check if this string looks like SQL.

looks_like_url property

Check if this string looks like a URL.

name property

The string value, used by TargetList filtering.

delete()

Delete this string literal (replace with empty string or remove assignment).

Note: This replaces the string with an empty string. For more complex deletion (removing the entire statement), use the containing target.

Returns

Result Result of the operation.

exists()

Check if this string literal still exists at the recorded location.

get_content()

Get the value of this string literal.

Returns

Result Result with string value in data field if successful.

rewrite(new_value=None, *, new_content=None)

Replace this string literal with a new value.

Parameters

new_value : str New string value (preferred parameter name for string literals). new_content : str Alias for new_value for API consistency with other targets.

Returns

Result Result of the operation.

Target(rejig)

Bases: ABC

Base class for all targets - things we can perform operations on.

Targets never raise exceptions for unsupported or failed operations. Instead, they return ErrorResult with details of what went wrong.

Subclasses should override methods to implement their specific behavior. The base implementation returns ErrorResult for all operations.

dry_run property

Check if we're in dry-run mode.

rejig property

Access the parent Rejig instance.

add_attribute(name, type_hint, default='None')

Add an attribute to this target.

add_class(name, body='pass', **kwargs)

Add a class to this target.

add_decorator(decorator)

Add a decorator to this target.

add_function(name, body='pass', **kwargs)

Add a function to this target.

add_import(import_statement)

Add an import statement to this target.

add_method(name, body='pass', **kwargs)

Add a method to this target.

delete()

Delete this target.

exists()

Check if this target exists in the codebase.

Default implementation returns False. Subclasses should override to provide proper existence checking.

Returns

bool True if the target exists, False otherwise.

find_class(name)

Find a class within this target. Returns ErrorTarget if not supported.

find_classes(pattern=None)

Find all classes within this target.

find_function(name)

Find a function within this target. Returns ErrorTarget if not supported.

find_functions(pattern=None)

Find all functions within this target.

find_method(name)

Find a method within this target. Returns ErrorTarget if not supported.

find_methods(pattern=None)

Find all methods within this target.

get_content()

Get the content/source code of this target.

insert_after(content)

Insert content after this target.

insert_before(content)

Insert content before this target.

insert_statement(statement, position='start')

Insert a statement into this target.

line(line_number)

Get a specific line of this target. Returns ErrorTarget if not supported.

lines(start, end)

Get a range of lines of this target. Returns ErrorTarget if not supported.

move_to(destination)

Move this target to a new location.

remove_decorator(decorator)

Remove a decorator from this target.

rename(new_name)

Rename this target.

replace(pattern, replacement)

Replace pattern in this target's content.

rewrite(new_content)

Replace the content of this target.

TargetList(rejig, targets)

Bases: Generic[T]

A list of targets that can be operated on uniformly.

Operations are applied to all targets, returning a BatchResult. This class is also returned by find operations (e.g., find_classes(), find_functions()).

Example

all_classes = rj.find_classes(pattern="^Test") results = all_classes.add_decorator("pytest.mark.slow") if results.partial_success: print(f"Modified {len(results.succeeded)} classes")

Add a copyright header to all file targets.

copyright_text : str Copyright holder text (e.g., "MyCompany Inc."). year : int | None Copyright year. Defaults to current year.

BatchResult Results of all operations.

files = rj.find_files("*/.py") files.add_copyright_header("MyCompany Inc.")

add_decorator(decorator)

Add a decorator to all targets.

add_decorator_all(decorator)

Alias for add_decorator().

add_license_header(license_name, copyright_holder=None, year=None)

Add a license header to all file targets.

Parameters

license_name : str License identifier: "MIT", "Apache-2.0", "GPL-3.0", "BSD-3-Clause", or "Proprietary". copyright_holder : str | None Copyright holder name. If None, uses a placeholder. year : int | None Copyright year. Defaults to current year.

Returns

BatchResult Results of all operations.

Examples

files = rj.find_files("*/.py") files.add_license_header("MIT")

convert_docstring_style(from_style, to_style)

Convert docstring style for all targets (FileTarget).

Parameters

from_style : str | None Source docstring style ("google", "numpy", "sphinx"), or None to auto-detect. to_style : str Target docstring style ("google", "numpy", "sphinx").

Returns

BatchResult Results of all operations.

Examples

files = rj.find_files("*/.py") files.convert_docstring_style("sphinx", "google")

convert_type_comments()

Convert type comments to inline annotations in all targets.

Converts

x = 1 # type: int

To: x: int = 1

Returns

BatchResult Results of all operations.

Examples

files = rj.find_files("*/.py") files.convert_type_comments()

delete()

Delete all targets.

delete_all()

Alias for delete().

filter(predicate)

Filter targets by a predicate.

first()

Get the first target, or None if empty.

generate_all_docstrings(style='google', overwrite=False)

Generate all docstrings for all targets (FileTarget).

This generates docstrings for all functions and methods in the files.

Parameters

style : str Docstring style: "google", "numpy", or "sphinx". Defaults to "google". overwrite : bool Whether to overwrite existing docstrings. Default False.

Returns

BatchResult Results of all operations.

Examples

files = rj.find_files("*/.py") files.generate_all_docstrings()

generate_docstrings(style='google', overwrite=False)

Generate docstrings for all targets (FunctionTarget/MethodTarget/ClassTarget).

Creates docstrings from function/method signatures including parameters, return type, and raised exceptions.

Parameters

style : str Docstring style: "google", "numpy", or "sphinx". Defaults to "google". overwrite : bool Whether to overwrite existing docstrings. Default False.

Returns

BatchResult Results of all operations.

Examples

funcs = rj.find_functions() funcs.generate_docstrings() methods = cls.find_methods() methods.generate_docstrings(style="numpy")

in_file(path)

Filter to targets in a specific file.

infer_type_hints(overwrite=False)

Infer and add type hints to all targets (FunctionTarget/MethodTarget).

Uses heuristics to infer types from: - Default parameter values (e.g., = 0 → int) - Parameter names (e.g., count → int, is_valid → bool)

Parameters

overwrite : bool If True, overwrite existing type hints. Default False.

Returns

BatchResult Results of all operations.

Examples

funcs = rj.find_functions() funcs.infer_type_hints()

insert_statement(statement, position='start')

Insert a statement in all targets.

last()

Get the last target, or None if empty.

matching(pattern)

Filter to targets whose name matches a regex pattern.

modernize_type_hints()

Modernize type hints in all targets (FileTarget).

Converts old-style type hints to Python 3.10+ syntax: - List[str] → list[str] - Dict[str, int] → dict[str, int] - Optional[str] → str | None - Union[str, int] → str | int

Returns

BatchResult Results of all operations.

Examples

files = rj.find_files("*/.py") files.modernize_type_hints()

remove_decorator(decorator)

Remove a decorator from all targets.

remove_type_hints()

Remove type hints from all targets (FunctionTarget/MethodTarget).

Removes return type annotations and parameter type annotations.

Returns

BatchResult Results of all operations.

Examples

funcs = rj.find_functions("^test_") funcs.remove_type_hints()

rename(pattern, replacement)

Rename all targets using pattern substitution.

rename_all(pattern, replacement)

Alias for rename().

replace_all(pattern, replacement)

Replace pattern in all targets that support it.

to_list()

Return the underlying list of targets.

Update the copyright year in all file targets.

Updates patterns like: - "Copyright 2023" -> "Copyright 2023-2024" - "Copyright 2023-2024" -> "Copyright 2023-2025"

new_year : int | None Target year. Defaults to current year.

BatchResult Results of all operations.

files = rj.find_files("*/.py") files.update_copyright_year()

with_docstrings()

Filter to targets that have docstrings.

Returns

TargetList[T] List of targets with docstrings.

Examples

funcs = rj.find_functions() with_docs = funcs.with_docstrings()

without_docstrings()

Filter to targets that don't have docstrings.

Returns

TargetList[T] List of targets without docstrings.

Examples

funcs = rj.find_functions() no_docs = funcs.without_docstrings() no_docs.generate_docstrings()

TextBlock(rejig, path)

Bases: Target

Raw text manipulation without AST parsing.

Use this for any text file where you need pattern-based manipulation without language-specific parsing.

Parameters

rejig : Rejig The parent Rejig instance. path : Path Path to the text file.

Examples

block = rj.text_block("README.md") block.find_pattern(r"version: .*").first().replace("version: 2.0.0")

Or use class method

block = TextBlock.from_file(Path("config.txt")) block.replace_pattern(r"DEBUG = \w+", "DEBUG = False")

file_path property

Path to the text file.

append(content)

Append content to the end of the file.

Parameters

content : str Content to append.

Returns

Result Result of the operation.

delete_line(line_number)

Delete a specific line.

Parameters

line_number : int 1-based line number to delete.

Returns

Result Result of the operation.

delete_lines(start, end)

Delete a range of lines (inclusive).

Parameters

start : int 1-based starting line number. end : int 1-based ending line number (inclusive).

Returns

Result Result of the operation.

exists()

Check if this file exists.

Returns

bool True if the file exists.

find_first(pattern, flags=0)

Find the first match of a pattern.

Parameters

pattern : str Regular expression pattern. flags : int Regex flags.

Returns

TextMatch | None First match, or None if not found.

find_pattern(pattern, flags=0)

Find all matches of a regex pattern.

Parameters

pattern : str Regular expression pattern to search for. flags : int Regex flags (e.g., re.IGNORECASE, re.MULTILINE).

Returns

TargetList[TextMatch] List of TextMatch targets for each match.

Examples

matches = block.find_pattern(r"TODO:.*") for match in matches: ... print(f"Line {match.line_number}: {match.text}")

from_file(path, dry_run=False) classmethod

Create a TextBlock from a file path without a Rejig instance.

Parameters

path : Path Path to the text file. dry_run : bool Whether to run in dry-run mode.

Returns

TextBlock A TextBlock for the specified file.

Examples

block = TextBlock.from_file(Path("config.txt")) block.replace_pattern(r"DEBUG = \w+", "DEBUG = False")

get_content()

Get the content of this file.

Returns

Result Result with file content in data field.

insert_at_line(line_number, content)

Insert content at a specific line.

Parameters

line_number : int 1-based line number to insert at. content : str Content to insert.

Returns

Result Result of the operation.

prepend(content)

Prepend content to the beginning of the file.

Parameters

content : str Content to prepend.

Returns

Result Result of the operation.

replace_pattern(pattern, replacement, count=0, flags=0)

Replace all occurrences of a pattern.

Parameters

pattern : str Regular expression pattern to replace. replacement : str Replacement string (can use backreferences like \1). count : int Maximum replacements (0 = unlimited). flags : int Regex flags.

Returns

Result Result of the operation.

rewrite(new_content)

Replace the entire content of this file.

Parameters

new_content : str New content for the file.

Returns

Result Result of the operation.

TextFileTarget(rejig, path)

Bases: Target

Target for any text file.

Provides basic line-based operations for text files that don't have a specific format (like Python, TOML, JSON, etc.).

Parameters

rejig : Rejig The parent Rejig instance. path : str | Path Path to the text file.

Examples

readme = rj.text_file("README.md") readme.get_content() readme.replace("old text", "new text")

file_path property

Path to the text file.

append(content)

Append content to the end of the file.

Parameters

content : str Content to append.

Returns

Result Result of the operation.

delete()

Delete this file.

Returns

Result Result of the operation.

delete_line(line_number)

Delete a specific line.

Parameters

line_number : int 1-based line number to delete.

Returns

Result Result of the operation.

delete_lines(start, end)

Delete a range of lines.

Parameters

start : int 1-based starting line number. end : int 1-based ending line number (inclusive).

Returns

Result Result of the operation.

exists()

Check if this file exists.

find_lines(pattern)

Find lines matching a pattern.

Parameters

pattern : str Regex pattern to search for.

Returns

list[tuple[int, str]] List of (line_number, line_content) tuples.

get_content()

Get the content of this file.

Returns

Result Result with file content in data field if successful.

get_line(line_number)

Get a specific line.

Parameters

line_number : int 1-based line number.

Returns

str | None The line content, or None if out of range.

insert_at_line(line_number, content)

Insert content at a specific line.

Parameters

line_number : int 1-based line number to insert at. content : str Content to insert.

Returns

Result Result of the operation.

line_count()

Get the number of lines in the file.

Returns

int Number of lines.

prepend(content)

Prepend content to the beginning of the file.

Parameters

content : str Content to prepend.

Returns

Result Result of the operation.

replace(pattern, replacement, count=0)

Replace pattern in the file content.

Parameters

pattern : str Regex pattern to search for. replacement : str Replacement string. count : int Maximum number of replacements (0 = all).

Returns

Result Result of the operation.

rewrite(new_content)

Replace the entire content of this file.

Parameters

new_content : str New content for the file.

Returns

Result Result of the operation.

TextMatch(rejig, path, match, content)

Bases: Target

Target for a pattern match within a text file.

Represents a specific match found by TextBlock.find_pattern(). Allows chaining operations on the matched text.

Parameters

rejig : Rejig The parent Rejig instance. path : Path Path to the file containing the match. match : re.Match The regex match object. content : str The full file content (for position calculations).

Examples

matches = rj.text_block("config.py").find_pattern(r"VERSION = ['"].*['"]") for match in matches: ... match.replace("VERSION = '2.0.0'")

end property

Character offset of match end.

file_path property

Path to the file containing this match.

groups property

Captured groups from the match.

line_number property

1-based line number of match start.

position property

Get line/column position of match.

Returns

MatchPosition Position information for the match.

start property

Character offset of match start.

text property

The matched text.

delete()

Delete this match.

Returns

Result Result of the operation.

exists()

Check if the match still exists in the file.

Returns

bool True if the exact matched text is still in the file.

get_content()

Get the matched text.

Returns

Result Result with matched text in data field.

insert_after(content)

Insert content after this match.

Parameters

content : str Content to insert.

Returns

Result Result of the operation.

insert_before(content)

Insert content before this match.

Parameters

content : str Content to insert.

Returns

Result Result of the operation.

replace(replacement)

Replace this match with new text.

Parameters

replacement : str Text to replace the match with.

Returns

Result Result of the operation.

TomlTarget(rejig, path)

Bases: Target

Target for a TOML configuration file.

Provides operations for reading, modifying, and querying TOML files like pyproject.toml.

Parameters

rejig : Rejig The parent Rejig instance. path : str | Path Path to the TOML file.

Examples

toml = rj.toml("pyproject.toml") toml.get("project.name") toml.set("project.version", "1.0.0") toml.get_section("tool.black")

file_path property

Path to the TOML file.

add_dependency(dependency)

Add a dependency to project.dependencies.

Parameters

dependency : str Dependency specification (e.g., "requests>=2.28.0").

Returns

Result Result of the operation.

delete(key_path)

Delete a key by key path.

Parameters

key_path : str | Sequence[str] Path to the key to delete: a dotted string, a list of literal segments, or a :class:KeyPath built with /.

Returns

Result Result of the operation.

exists()

Check if this TOML file exists.

get(key_path, default=None)

Get a value by key path.

Parameters

key_path : str | Sequence[str] Path to the key: a dotted string ("project.name", "tool.black.line-length"), a list of literal segments (["tool", "black", "line-length"]), or a :class:KeyPath built with / (KeyPath("tool") / "black" / "line-length" — use this when a key contains a literal .). default : Any Default value if key not found.

Returns

Any The value at the key path, or default if not found.

Examples

toml.get("project.name") "myproject" toml.get("tool.black.line-length", 88) 110

get_content()

Get the raw content of the TOML file.

Returns

Result Result with file content in data field if successful.

get_data()

Get the parsed TOML data as a dictionary.

Returns

Result Result with parsed dict in data field if successful.

get_dependencies()

Get project dependencies from pyproject.toml.

get_optional_dependencies(group)

Get optional dependencies for a group.

get_project_name()

Get the project name from pyproject.toml.

get_project_version()

Get the project version from pyproject.toml.

get_section(section_path)

Get a section as a dictionary.

Parameters

section_path : str Dotted path to the section (e.g., "tool.black").

Returns

dict | None The section dictionary, or None if not found.

get_tool_config(tool_name)

Get configuration for a specific tool.

Parameters

tool_name : str Tool name (e.g., "black", "ruff", "mypy").

Returns

dict | None Tool configuration, or None if not found.

has_key(key_path)

Check if a key exists.

Parameters

key_path : str Dotted path to check.

Returns

bool True if the key exists.

keys(section_path=None)

Get keys at a section path.

Parameters

section_path : str | None Dotted path to section, or None for root keys.

Returns

list[str] List of keys at the section.

remove_dependency(package_name)

Remove a dependency from project.dependencies.

Parameters

package_name : str Package name to remove (version spec ignored).

Returns

Result Result of the operation.

rewrite(new_content)

Replace the entire content of the TOML file.

Validates the content is valid TOML before writing.

Parameters

new_content : str New TOML content.

Returns

Result Result of the operation.

set(key_path, value)

Set a value by key path.

Parameters

key_path : str | Sequence[str] Path to the key: a dotted string ("project.version"), a list of literal segments, or a :class:KeyPath built with /. value : Any Value to set.

Returns

Result Result of the operation.

Examples

toml.set("project.version", "2.0.0") toml.set("tool.black.line-length", 110)

set_project_version(version)

Set the project version in pyproject.toml.

set_section(section_path, data)

Set an entire section.

Parameters

section_path : str Dotted path to the section (e.g., "tool.ruff"). data : dict Section data to set.

Returns

Result Result of the operation.

set_tool_config(tool_name, config)

Set configuration for a specific tool.

Parameters

tool_name : str Tool name (e.g., "black", "ruff"). config : dict Tool configuration.

Returns

Result Result of the operation.

YamlTarget(rejig, path)

Bases: Target

Target for a YAML configuration file.

Provides operations for reading, modifying, and querying YAML files.

Parameters

rejig : Rejig The parent Rejig instance. path : str | Path Path to the YAML file.

Examples

yaml_file = rj.yaml("config.yaml") yaml_file.get("database.host") yaml_file.set("database.port", 5432)

file_path property

Path to the YAML file.

append_to_list(key_path, value)

Append a value to a list at the specified key path.

Parameters

key_path : str Dotted path to the list. value : Any Value to append.

Returns

Result Result of the operation.

delete(key_path)

Delete a key by key path.

Parameters

key_path : str | Sequence[str] Path to the key to delete: a dotted string, a list of literal segments, or a :class:KeyPath built with /.

Returns

Result Result of the operation.

exists()

Check if this YAML file exists.

get(key_path, default=None)

Get a value by key path.

Parameters

key_path : str | Sequence[str] Path to the key, in any of three forms: a dotted string ("database.host", "servers.0.name"), a list of literal segments (["database", "host"]), or a :class:KeyPath built with / (KeyPath("database") / "host" — use this when a key contains a literal .). default : Any Default value if key not found.

Returns

Any The value at the key path, or default if not found.

Examples

yaml_file.get("database.host") "localhost" yaml_file.get("database.port", 5432) 5432 yaml_file.get(["security", "ignore", "CVE-2026.0001"]) # literal dot

get_content()

Get the raw content of the YAML file.

Returns

Result Result with file content in data field if successful.

get_data()

Get the parsed YAML data.

Returns

Result Result with parsed data in data field if successful.

get_section(section_path)

Get a section as a dictionary.

Parameters

section_path : str Dotted path to the section.

Returns

dict | None The section dictionary, or None if not found.

has_key(key_path)

Check if a key exists.

Parameters

key_path : str Dotted path to check.

Returns

bool True if the key exists.

keys(section_path=None)

Get keys at a section path.

Parameters

section_path : str | None Dotted path to section, or None for root keys.

Returns

list[str] List of keys at the section.

remove_from_list(key_path, value)

Remove a value from a list at the specified key path.

Parameters

key_path : str Dotted path to the list. value : Any Value to remove.

Returns

Result Result of the operation.

rewrite(new_content)

Replace the entire content of the YAML file.

Parameters

new_content : str New YAML content.

Returns

Result Result of the operation.

set(key_path, value)

Set a value by key path.

Parameters

key_path : str | Sequence[str] Path to the key: a dotted string ("database.host"), a list of literal segments (["database", "host"]), or a :class:KeyPath built with / (KeyPath("database") / "host" — use this when a key contains a literal .). value : Any Value to set.

Returns

Result Result of the operation.

Examples

yaml_file.set("database.host", "localhost") yaml_file.set("database.port", 5432) yaml_file.set(["security", "ignore", "CVE-2026.0001"], "reviewed")

set_section(section_path, data)

Set an entire section.

Parameters

section_path : str Dotted path to the section. data : dict Section data to set.

Returns

Result Result of the operation.