Skip to main content

Integrating extra metadata into attr.ib()

Project description

PyPI version supported Python versions Travis build status source on GitHub

Integrating extra metadata into attr.ib()

Example

With a little luck a better example will be provided later but for now, here’s something.

A dev in #python was interested in having click build them attrs-defined configuration objects. Here’s a basic solution for that with the click options being defined on the attrs class attributes via a custom exttr keyword argument click=.

import collections
import sys

import attr
import click
import exttr


exttr.register_keywords(
    exttr.Keyword(name='click'),
)


@attr.s
class Configuration:
    foo = exttr.ib(click=click.option('--red'))


def main(configuration):
    print(configuration)

def clicked_fields(cls):
    fields = collections.OrderedDict()

    for field in attr.fields(cls):
        decorator = exttr.get(cls, field.name, 'click')

        if decorator is None:
            continue

        fields[field.name] = decorator

    return fields


def build_click(f, cls, command_or_group):
    fields = clicked_fields(cls)

    def cli(*args, **kwargs):
        configuration = cls(*args, **kwargs)

        return f(configuration)

    for name, decorator in reversed(fields.items()):
        before = getattr(cli, '__click_params__', [])

        cli = decorator(cli)

        after = getattr(cli, '__click_params__', [])
        new = after[len(before):]

        if len(new) == 1:
            new, = new
            new.name = name

    return command_or_group(cli)


click_main = build_click(
    f=main,
    cls=Configuration,
    command_or_group=click.command(),
)


sys.argv[1:] = ['--red', 'burgundy']
try:
    click_main()
except SystemExit:
    pass

Output:

Configuration(foo='burgundy')

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

exttr-2019.2.2.tar.gz (20.7 kB view hashes)

Uploaded Source

Built Distribution

exttr-2019.2.2-py3-none-any.whl (6.6 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