### Generated __repr__ format example Source: https://context7.com/cleder/crepr/llms.txt Example of a class before and after applying crepr, including usage. ```python # Input class: class Person: def __init__(self, name: str, *, age: int) -> None: self.name = name self.age = age # After running: crepr add person.py --inline # The class becomes: class Person: def __init__(self, name: str, *, age: int) -> None: self.name = name self.age = age def __repr__(self) -> str: """Create a string (c)representation for Person.""" return (f'{self.__class__.__module__}.{self.__class__.__name__}(' f'name={self.name!r}, ' f'age={self.age!r}, ' ')') # Usage: >>> from mymodule.person import Person >>> p = Person('Alice', age=30) >>> p mymodule.person.Person(name='Alice', age=30, ) >>> repr(p) "mymodule.person.Person(name='Alice', age=30, )" ``` -------------------------------- ### Example: Using the Generated __repr__ Source: https://github.com/cleder/crepr/blob/develop/README.md Shows how to instantiate a class with a generated __repr__ method and display its representation. This demonstrates the practical output of the crepr tool. ```python >>> from tests.classes.kw_only_test import KwOnly >>> kwo = KwOnly('Christian', age=25) >>> kwo tests.classes.kw_only_test.KwOnly(name='Christian', age=25, ) ``` -------------------------------- ### Example class with **kwargs Source: https://context7.com/cleder/crepr/llms.txt Demonstration of a class definition that accepts **kwargs. ```python class ConfigLoader: def __init__(self, path: str, **kwargs: int) -> None: self.path = path self.kwargs = kwargs ``` -------------------------------- ### Example: Adding __repr__ to KwOnly Class Source: https://github.com/cleder/crepr/blob/develop/README.md Demonstrates adding a __repr__ method to a Python class using crepr. The generated method uses the class's __init__ arguments to create a representation. ```python class KwOnly: def __init__(self, name: str, *, age: int) -> None: self.name = name self.age = age ``` ```python class KwOnly: def __init__(self, name: str, *, age: int) -> None: self.name = name self.age = age def __repr__(self) -> str: """Create a string (c)representation for KwOnly.""" return ( f'{self.__class__.__module__}.{self.__class__.__name__}( f'name={self.name!r}, f'age={self.age!r}, ')') ``` -------------------------------- ### Install crepr Package Source: https://github.com/cleder/crepr/blob/develop/README.md Install the crepr package using pip. This command is used to add the functionality to your Python environment. ```bash pip install crepr ``` -------------------------------- ### Automate __repr__ insertion with a full workflow Source: https://context7.com/cleder/crepr/llms.txt Demonstrates a complete workflow for programmatically generating and optionally applying __repr__ methods to a file. ```python import pathlib from crepr.crepr import ( get_module, create_repr, insert_changes, ) def add_repr_to_file(file_path: str, apply: bool = False) -> str: """Add __repr__ methods to all classes in a file.""" path = pathlib.Path(file_path) module = get_module(path) # Generate changes for classes without existing __repr__ changes = create_repr(module, kwarg_splat="{}", ignore_existing=True) if not changes: return "No classes need __repr__ methods" # Apply changes to source modified_source = insert_changes(module, changes) result = "\n".join(modified_source) if apply: with path.open(mode="w", encoding="UTF-8") as f: f.write(result) return f"Modified {len(changes)} classes" return result # Preview changes print(add_repr_to_file("models.py")) # Apply changes print(add_repr_to_file("models.py", apply=True)) ``` -------------------------------- ### Extract __init__ parameters with get_init_args Source: https://context7.com/cleder/crepr/llms.txt Retrieves parameter metadata from a class's __init__ method. Useful for inspecting constructor signatures programmatically. ```python from crepr.crepr import get_init_args class Example: def __init__(self, name: str, count: int = 0) -> None: self.name = name self.count = count init_args, lineno, source_lines = get_init_args(Example) if init_args: for param_name, param in init_args.items(): if param_name != "self": print(f"Parameter: {param_name}, kind: {param.kind}") ``` -------------------------------- ### Customize **kwargs formatting Source: https://context7.com/cleder/crepr/llms.txt Configure how keyword arguments are represented in the generated string. ```bash crepr add my_module.py --kwarg-splat "{}" crepr add my_module.py --kwarg-splat "..." ``` -------------------------------- ### Generate __repr__ source lines with create_repr_lines Source: https://context7.com/cleder/crepr/llms.txt Produces the source code lines for a __repr__ method based on provided parameter definitions. ```python import inspect from crepr.crepr import create_repr_lines init_args = { "self": inspect.Parameter("self", inspect.Parameter.POSITIONAL_OR_KEYWORD), "name": inspect.Parameter("name", inspect.Parameter.POSITIONAL_OR_KEYWORD), "age": inspect.Parameter("age", inspect.Parameter.KEYWORD_ONLY), } lines = create_repr_lines("Person", init_args, kwarg_splat="{}") for line in lines: print(line) ``` -------------------------------- ### Introspect modules with get_module Source: https://context7.com/cleder/crepr/llms.txt Programmatically load a module from a file path for introspection. ```python import pathlib from crepr.crepr import get_module, CreprError try: module = get_module(pathlib.Path("my_module.py")) print(f"Loaded module: {module.__name__}") except CreprError as e: print(f"Error: {e.message}") ``` -------------------------------- ### Handle existing __repr__ methods Source: https://context7.com/cleder/crepr/llms.txt Force generation of a new __repr__ method even if one already exists. ```bash crepr add my_module.py --ignore-existing --inline ``` -------------------------------- ### get_module Source: https://context7.com/cleder/crepr/llms.txt Loads a Python module from a file path for introspection purposes. ```APIDOC ## get_module(path) ### Description Loads a Python module from a given file path to allow for introspection of classes and their __init__ methods. ### Parameters #### Path Parameters - **path** (pathlib.Path) - Required - The file path to the Python module to be loaded. ### Response - **module** (module) - The loaded Python module object. ### Errors - **CreprError** - Raised if the module cannot be loaded or processed. ``` -------------------------------- ### Apply Changes Inline Source: https://github.com/cleder/crepr/blob/develop/README.md Command to apply the generated __repr__ changes directly to the specified Python file. Use this option when you are satisfied with the diff. ```bash crepr add tests/classes/kw_only_test.py --inline ``` -------------------------------- ### Add __repr__ Method to Classes Source: https://github.com/cleder/crepr/blob/develop/README.md Use the 'add' command to automatically generate and add __repr__ methods to all classes within a specified Python file. This command can optionally display changes as a diff or apply them directly to the file. ```bash crepr add [--kwarg-splat "{}"] [--diff/--inline] ``` -------------------------------- ### Generate module-wide __repr__ changes with create_repr Source: https://context7.com/cleder/crepr/llms.txt Analyzes a module to identify classes needing __repr__ methods and generates the corresponding source code changes. ```python import pathlib from crepr.crepr import get_module, create_repr, insert_changes # Load module module = get_module(pathlib.Path("my_module.py")) # Generate changes (returns dict mapping line numbers to Change objects) changes = create_repr(module, kwarg_splat="{}", ignore_existing=True) for lineno, change in changes.items(): print(f"Class: {change['class_name']} at line {lineno}") print("Generated lines:") for line in change["lines"]: print(line) ``` -------------------------------- ### Remove __repr__ Method from Classes Source: https://github.com/cleder/crepr/blob/develop/README.md Use the 'remove' command to remove existing __repr__ methods from all classes within a specified Python file. This command can also display changes as a diff or apply them directly to the file. ```bash crepr remove [--diff/--inline] ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.