Skip to content
/ crepr Public

Create a ❤️__repr__🤗️ for your python classes from the definition found in __init__

License

Notifications You must be signed in to change notification settings

cleder/crepr

Repository files navigation

crepr

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.

Tests codecov pre-commit MyPy Black MIT License Python Version PyPI - Version Status

Features

  • 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

Install

pip install crepr

Usage

To 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]

Options

  • <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.

Example

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 = age

The command:

❯ crepr add tests/classes/kw_only_test.py

produces

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 --inline

Give your representations some love.

❤️.__repr__(self) -> str:

About

Create a ❤️__repr__🤗️ for your python classes from the definition found in __init__

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published