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.2.tar.gz
(20.7 kB
view details)
Built Distribution
File details
Details for the file exttr-2019.2.2.tar.gz
.
File metadata
- Download URL: exttr-2019.2.2.tar.gz
- Upload date:
- Size: 20.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/40.8.0 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.7.2
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 961c733f3ea00727f099904a4279fd44551754913c3aeed910837bf4ed0f7e45 |
|
MD5 | f1573fa6b294875d1d04cd1bb193a15f |
|
BLAKE2b-256 | ef6cb5872c040b75ce5b447c41ab9abedc6bcdb243a53734ae6a91bab1b072c8 |
File details
Details for the file exttr-2019.2.2-py3-none-any.whl
.
File metadata
- Download URL: exttr-2019.2.2-py3-none-any.whl
- Upload date:
- Size: 6.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/40.8.0 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.7.2
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 5b6898fc3d9db71614805cd09ca7490495fa65a0580a2ad58c9ad9778913e468 |
|
MD5 | 7de8bb2afe6ddffa7f7ae3b49e953737 |
|
BLAKE2b-256 | c9ce4c1b8fb5be4aae1570c438c7162296e1c7a3a247bd65a2521af0d216ec1a |