Skip to main content

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

Project description

crepr

Create a __repr__ for your python classes.

A Python script that takes a file path as a command-line argument, imports the specified file, and creates a __repr__ method for each class defined in the module. It uses the definition found in the __init__ method of the class. 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

Install

pip install crepr

Usage

 crepr --help
Usage: crepr [OPTIONS] FILE_PATH

  Create a __repr__ method for each class of a python file.

Arguments:
  FILE_PATH  [required]

Options:
  --install-completion [bash|zsh|fish|powershell|pwsh]
                                  Install completion for the specified shell.
  --show-completion [bash|zsh|fish|powershell|pwsh]
                                  Show completion for the specified shell, to
                                  copy it or customize

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 tests/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, )

Give your representations some love.

❤️.__repr__(self) -> str:

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

crepr-0.2.0.tar.gz (6.6 kB view hashes)

Uploaded Source

Built Distribution

crepr-0.2.0-py3-none-any.whl (6.5 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page