Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 14418

In python Attrs package, how to add a field in the field_transformer function?

$
0
0

The documentation for the python Attrs, the Automatic Field Transformation and Modification section states

...You can add converters, change types, and even remove attributescompletely or create new ones!" (emphasis added).

It also states in the API documentation regarding Attribute that "You should never instantiate this class yourself."

However, if you attempt to add a field in the field_transformer function you cannot, at least with the attrs.field() function.

    import attrs    def transformer(cls, fields):        fields.append(attrs.field(name='bar'))        return fields    @attrs.define(field_transformer=transformer)    class A:        pass    A(bar=1)

This fails with a TypeError: field() got an unexpected keyword argument 'name'. If you use "alias" instead you get AttributeError: '_CountingAttr' object has no attribute 'name'.

What is the proper way to add a field in field_transformer function?

Edit:I was able to get things to work with the following:

import attrsdef transformer(cls, fields):            ca = attrs.field()    f = attrs.Attribute.from_counting_attr(name="foo", ca=ca, type=int)    return [f, *fields]@attrs.define(field_transformer=transformer)class A:    passA(foo=1)

Viewing all articles
Browse latest Browse all 14418

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>