[Python-ideas] JavaScript-Style Object Creation in Python (using a constructor function instead of a class to create objects)

Eric V. Smith eric at trueblade.com
Wed May 17 05:11:11 EDT 2017

On 5/16/17 5:04 PM, Guido van Rossum wrote:
> Stephen,
> What features of attrs specifically solve your use cases?

Also not Stephan!

As others have said, it's the "tupleness" of namedtuple that has bitten me.

Also, option mutability is key for my use cases.

One use case that attrs satisfies (as does namedtuple) that I'd like to 
make sure we allow for in any solution is dynamically creating classes 
where you don't know the field names until runtime. I run in to this 
when reading anything with columnar metadata, like databases or CSV 
files. The attr.s "these" parameter solves this for me:	

fields = ['a', 'b', 'c']

@attr.s(these={f:attr.ib() for f in fields})
class Foo:

f = Foo(1, 2, 3)

Foo(a=1, b=2, c=3)

Mutable default values is a foot-gun. attrs solves it in a similar way 
to my "namedlist" on PyPI.

I'm moving to abandon namedlist and replace it with attrs: the namedlist 
API is horrible, but a logical (to me!) extension from namedtuple. I 
mainly wrote it as an exercise in dynamically creating classes using the 
ast module (as opposed to namedtuple where we build a string definition 
of the class and exec that).


More information about the Python-ideas mailing list