Create a __repr__ for your python classes.
crepr is a Python script that takes a file name as a command-line argument, imports the specified module, and then adds or removes a __repr__ method for each class defined in the module.
It uses the definition found in the __init__ method of the class to create a useful representation of the object.
It is pronounced /kɹeɪpr/, like 🇳🇿 crêpe.
Have a look at the blog-post Love Your Representation for the rationale of this package.
- Automatically generates
__repr__methods for all classes in a Python file - Uses the
__init__method's arguments to create a meaningful representation - Can add or remove
__repr__methods - Provides options to display the diff or apply changes directly to the file
pip install creprTo add a __repr__ method to all classes in a file:
crepr add <file_name> [--kwarg-splat "{}"] [--diff/--inline]To remove the __repr__ method from all classes in a file:
crepr remove <file_name> [--diff/--inline]<file_name>: The name of the Python file to process.--kwarg-splat: The string to use for the **kwargs splat (default: "{}").--diff: Display the diff of the changes.--inline: Apply the changes directly to the file.--ignore-existing: Add__repr__regardless if one exists
Given the file tests/classes/kw_only_test.py with the contents:
class KwOnly:
def __init__(self, name: str, *, age: int) -> None:
self.name = name
self.age = ageThe command:
❯ crepr add tests/classes/kw_only_test.pyproduces
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}, '
')')The repr() of an instance of this class will be:
>>> from tests.classes.kw_only_test import KwOnly
>>> kwo = KwOnly('Christian', age=25)
>>> kwo
tests.classes.kw_only_test.KwOnly(name='Christian', age=25, )Apply the changes to the file with:
❯ crepr add tests/classes/kw_only_test.py --inlineGive your representations some love.
❤️.__repr__(self) -> str: