Integrating extra metadata into attr.ib()
Project description
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
Release history Release notifications | RSS feed
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.1.tar.gz
(20.4 kB
view hashes)