1. 27

A short and dumb example:

import attr

@attr.s
class Vec2(object):
        x = attr.ib()
        y = attr.ib()

pos = Vec2(42, -42)
  1.  

  2. 11

    attrs has been successful enough that PSF CPython core is investigating adding a stripped-down version to the 3.7 standard library.

    1. 8

      It’s not the PSF, it’s the CPython core developers. The PSF does not direct the development of the Python language.

    2. 6

      This looks really nice. Simple, does what it does, gets out of the way.

      Sounded unnecessary, but http://www.attrs.org/en/stable/why.html explains the rationale well, in contrast with named tuples and other things.

      1. 3

        This gets close to a thing I enjoy in Swift:

        struct Vec2 {
            var x: Float
            var y: Float
        }
        
        var pos = Vec2(x: 42, y: -42)
        

        Free memberwise initializer for structs. You can also provide default values by appending = val to the members. The @dataclass proposal looks closer still.

        You don’t get free comparison operators (but it’s getting there) so this is nicer in that regard.

        1. 3

          Yup I think this is basically “value types” for Python! I wanted this a long time ago!

          Namedtuple was close but the syntax is a bit awkward.

          1. 3

            In C99 you can do this:

            typedef struct {
                    float x;
                    float y;
            } Vec2;
            
            Vec2 pos_foo = {42, -42};
            
            // or using designated initializers (x will be 0 in this case):
            Vec2 pos_bar = {.y = 42 };
            
            // or using compound literals:
            draw(foo, (Vec2){42, -42});
            
            // more with designated initializers (everything else will be 0):
            enum { FOO, BAR, BAZ, COUNT };
            Vec2 pos[COUNT] = { [BAR] = {.y = 42} };
            
            1. 2

              It’s funny that statically typed languages like Swift and Go cover this better than a dynamically typed language like Python ;-)

              1. 1

                Not sure what this has to do with dynamic vs static typing.