Targets¶
Targets are objects representing code elements you can inspect or modify.
Base Classes¶
Target¶
The abstract base class for all targets.
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.
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
¶
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_decorator(decorator)
¶
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_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_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_to_typed_dict(total=True)
¶
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_methods(pattern=None)
¶
find_methods_without_docstrings()
¶
generate_all_dunders(overwrite=False)
¶
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_hash(overwrite=False)
¶
generate_init(overwrite=False)
¶
generate_repr(overwrite=False)
¶
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_source()
¶
move_to(destination)
¶
remove_attribute(attr_name)
¶
remove_base_class(base_class)
¶
remove_decorator(decorator)
¶
remove_object_base()
¶
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)
¶
exists()
¶
Check if this code block still exists.
find_at_line(rejig, file_path, line_number)
classmethod
¶
get_content()
¶
Get the content of this code block.
Returns¶
Result
Result with block content in data field if successful.
indent(levels=1)
¶
insert_after(content)
¶
insert_before(content)
¶
move_to(destination)
¶
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)
¶
rewrite(new_content)
¶
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.
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_copyright_header(copyright_text, year=None)
¶
Add a copyright header to this file.
Parameters¶
copyright_text : str Copyright holder text (e.g., "MyCompany Inc."). year : int | None Copyright year. Defaults to current year.
Returns¶
Result Result of the operation.
Examples¶
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_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)
¶
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_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_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_type_comments_to_annotations()
¶
exists()
¶
Check if this file exists.
find_class(name)
¶
find_classes(pattern=None)
¶
find_directives()
¶
find_function(name)
¶
find_functions(pattern=None)
¶
find_imports()
¶
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_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_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_content()
¶
has_header()
¶
line(line_number)
¶
lines(start, end)
¶
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()
¶
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_noqa()
¶
remove_all_type_ignores()
¶
remove_from_all(name)
¶
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_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)
¶
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_copyright_year(new_year=None)
¶
Update the copyright year in this file's header.
Updates patterns like: - "Copyright 2023" -> "Copyright 2023-2024" - "Copyright 2023-2024" -> "Copyright 2023-2025"
Parameters¶
new_year : int | None Target year. Defaults to current year.
Returns¶
Result Result of the operation.
Examples¶
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
¶
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_decorator(decorator)
¶
add_docstring_example(example)
¶
add_docstring_raises(exception, description)
¶
add_docstring_returns(description)
¶
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_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_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()
¶
convert_to_async()
¶
convert_to_sync()
¶
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()
¶
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_before_match(pattern, code)
¶
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)
¶
remove_decorator(decorator)
¶
remove_parameter(param_name)
¶
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)
¶
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_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)
¶
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)
¶
delete_key(section, key)
¶
delete_section(section)
¶
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_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_int(section, key, default=0)
¶
get_section(section)
¶
has_key(section, key)
¶
has_section(section)
¶
keys(section)
¶
rewrite(new_content)
¶
set(section, key, value)
¶
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)
¶
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_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)
¶
keys(section_path=None)
¶
rewrite(new_content)
¶
set(key_path, value)
¶
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)
¶
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)
¶
insert_after(content)
¶
insert_before(content)
¶
move_to(destination)
¶
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)
¶
rewrite(new_content)
¶
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_noqa(codes=None)
¶
add_pylint_disable(codes)
¶
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")
exists()
¶
Check if this line exists in the file.
get_content()
¶
insert_after(content)
¶
insert_before(content)
¶
remove_fmt_skip()
¶
remove_no_cover()
¶
remove_pylint_disable()
¶
remove_type_ignore()
¶
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
¶
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_decorator(decorator)
¶
add_docstring_example(example)
¶
add_docstring_raises(exception, description)
¶
add_docstring_returns(description)
¶
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_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_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()
¶
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()
¶
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()
¶
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_before_match(pattern, code)
¶
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_parameter(param_name)
¶
remove_type_hints()
¶
rename(new_name)
¶
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_match(pattern, code)
¶
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)
¶
update_docstring_param(param_name, description)
¶
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_function(name, body='pass', **kwargs)
¶
add_import(import_statement)
¶
exists()
¶
Check if this module exists.
find_class(name)
¶
find_classes(pattern=None)
¶
find_function(name)
¶
find_functions(pattern=None)
¶
get_content()
¶
Get the content of this module's file.
Returns¶
Result
Result with file content in data field if successful.
line(line_number)
¶
lines(start, end)
¶
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
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_copyright_header(copyright_text, year=None, recursive=True)
¶
Add a copyright header to all Python files in this package.
Parameters¶
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.
Returns¶
Result Result of the operation.
Examples¶
pkg = rj.package("mypackage/") pkg.add_copyright_header("Copyright 2024 MyCompany")
add_import(import_statement)
¶
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_subpackage(name, init_content='')
¶
exists()
¶
Check if this package exists (directory with init.py).
find_class(name)
¶
find_classes(pattern=None)
¶
find_function(name)
¶
find_functions(pattern=None)
¶
find_module(name)
¶
find_subpackage(name)
¶
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()
¶
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_copyright_year(new_year=None, recursive=True)
¶
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"
Parameters¶
new_year : int | None Target 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.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 |
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)
¶
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_copyright_header(copyright_text, year=None)
¶
Add a copyright header to all file targets.
Parameters¶
copyright_text : str Copyright holder text (e.g., "MyCompany Inc."). year : int | None Copyright year. Defaults to current year.
Returns¶
BatchResult Results of all operations.
Examples¶
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()
¶
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()
¶
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_copyright_year(new_year=None)
¶
Update the copyright year in all file targets.
Updates patterns like: - "Copyright 2023" -> "Copyright 2023-2024" - "Copyright 2023-2024" -> "Copyright 2023-2025"
Parameters¶
new_year : int | None Target year. Defaults to current year.
Returns¶
BatchResult Results of all operations.
Examples¶
files = rj.find_files("*/.py") files.update_copyright_year()
with_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)
¶
delete_line(line_number)
¶
delete_lines(start, end)
¶
find_first(pattern, flags=0)
¶
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()
¶
insert_at_line(line_number, content)
¶
prepend(content)
¶
replace_pattern(pattern, replacement, count=0, flags=0)
¶
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)
¶
delete_line(line_number)
¶
delete_lines(start, end)
¶
exists()
¶
Check if this file exists.
find_lines(pattern)
¶
get_content()
¶
get_line(line_number)
¶
insert_at_line(line_number, content)
¶
prepend(content)
¶
replace(pattern, replacement, count=0)
¶
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
¶
start
property
¶
Character offset of match start.
text
property
¶
The matched text.
exists()
¶
Check if the match still exists in the file.
Returns¶
bool True if the exact matched text is still in the file.
insert_after(content)
¶
insert_before(content)
¶
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)
¶
delete(key_path)
¶
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_tool_config(tool_name)
¶
has_key(key_path)
¶
keys(section_path=None)
¶
remove_dependency(package_name)
¶
rewrite(new_content)
¶
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)
¶
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)
¶
delete(key_path)
¶
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_section(section_path)
¶
has_key(key_path)
¶
keys(section_path=None)
¶
remove_from_list(key_path, value)
¶
rewrite(new_content)
¶
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")