Skip to main content
Join the official 2019 Python Developers SurveyStart the survey!

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.

Files for exttr, version 2019.2.2
Filename, size File type Python version Upload date Hashes
Filename, size exttr-2019.2.2-py3-none-any.whl (6.6 kB) File type Wheel Python version py3 Upload date Hashes View hashes
Filename, size exttr-2019.2.2.tar.gz (20.7 kB) File type Source Python version None Upload date Hashes View hashes

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN SignalFx SignalFx Supporter DigiCert DigiCert EV certificate StatusPage StatusPage Status page