Live data from Hacker News

Using attrs for everything in Python

glyph.twistedmatrix.com

41–50 of 105 posts

Re: Using attrs for everything in Python

#41
If you just want an object that stores a few attributes and you don't want to define a namedtuple, you can use types.SimpleNamespace in Python >= 3.3: https://docs.python.org/3.5/library/types.html#types.SimpleN...

It's a pretty unknown feature from the stdlib, but sometimes very useful.

Re: Using attrs for everything in Python

#42
post #40

In the end, this is about defining a typed structure. "@attr" plus validator constraints is effectively a typed structure. Python got further with minimal declarations than any other mainstream language. Yet there's a demand for typed variables. This is going into future Python, although in a strange and clunky way, because types don't fit the syntax. We seem to be converging on a consensus on when to declare types.…

The latest version does allow you to decorate variables with types... Not sure its doing anything with them yet.

Re: Using attrs for everything in Python

#43

Earlier quoted context omitted.

Also, read the post and looked over the docs, and don't see any explanation of what `.s` and `.ib` is supposed to mean (though I can figure out from context). Does anyone know what the letters stand for? Struct and instance b…???

> They are a concise and highly readable way to write attrs and attrib with an explicit namespace. > For those who can’t swallow that API at all, attrs comes with serious business aliases: attr.attrs and attr.attrib. I'm definitely in the can't swallow camp. There's no precedent for using attribute namespaces to name things with half the name on one side and half the name on the other side, so who the hell does this…

If you use `import ... as ...`, you can rename them to nicer names (full gist at [0]):

    from attr import (
        s as AttributedModel,
        ib as attribute,
    )
    
    @AttributedModel
    class Bar(object):
        x = attribute()
        y = attribute()


0: https://gist.github.com/gknoy/6e884fce3edda08a1566823fec37ba...

Re: Using attrs for everything in Python

#44
post #40

In the end, this is about defining a typed structure. "@attr" plus validator constraints is effectively a typed structure. Python got further with minimal declarations than any other mainstream language. Yet there's a demand for typed variables. This is going into future Python, although in a strange and clunky way, because types don't fit the syntax. We seem to be converging on a consensus on when to declare types.…

The latest version does allow you to decorate variables with types... Not sure its doing anything with them yet.

It's not. See [1]. The retrofitting of type declarations to Python is taking a very strange path.

(Evil interpretation: this is an effort by Python's little tin god to sabotage PyPy. Type information is a huge win for a compiler; it can now generate hard code for a specific type. It doesn't help CPython much, since inside CPython everything is a CObject. With type information, one could write things like NumPy, with its arrays of uniform type and functions which operate on them, in Python. The PyPy compiler could then generate efficient code for them. This would make PyPy the primary Python compiler. But if type annotation isn't enforced in CPython, code won't port reliably to a compiler which enforces it.)

[1] https://www.python.org/dev/peps/pep-0484/

Re: Using attrs for everything in Python

#45
Haven't finished reading yet but I just wanted to say that this _really_ resonates with me...

> You know what? I’m done. 20 lines of code so far and we don’t even have a class that does anything; the hard part of this problem was supposed to be the quaternion solver, not “make a data structure which can be printed and compared”.

YES. I don't know much about attrs, but if it helps solve this, I'm in.

Re: Using attrs for everything in Python

#46
post #36

I can't find it at the moment but wasn't there another solution to this problem where you could just populate an object at will (like matlab's struct for instance)? IIRC it was dict-based and allowed something like foo = SomePythonWizardry() foo.x = 1 foo.a.b = 2 print( foo ) #yields e.g. foo.x = 1, foo.a.b = 2 Or am I just dreaming? It would be all the goodness and none of the weird syntax.

I think if you import mock you can create mock.Mock() instances that allow you to assign fields that way.

Re: Using attrs for everything in Python

#48
post #35

It feels a bit hampered by "bad" design decisions to me I think its safe to say that the current view of what decorators do is, a) filter things going to functions (so they error, or hit a cache), or b) register a function with another library (e.g. flask path decorator) This library does a lot more than that, so it seems that maybe a metaclass (which exists to mutate the class's creation) would be more appropriate?…

Your view of what decorators doesn't seem to reflect the usage I've experienced writing Python professionally over the last 10 years. Decorators take an object and return a object (by convention a callable, although this isn't enforced in the slightest). Maybe they modify a function or method signature, maybe it produces an unrelated object, or maybe one augments the object by adding side effects like caching or logg…

I know how decorators work and you might be missing the point I was making by a fair mile

The following don't mutate the mental map of how the function works, its "this function is still what I typed": "add logging" "add tracing" "register functions/objects for various reasons"

The following act as a filtering role, the inside isn't "changed", the mental map becomes "This function will operate within this feature in some way, but otherwise is still what I typed": "enable type validation" "change output formats to json/xml/yaml" "swap out implementations for global functions/vars" (assuming the implementations are comparable)

The following is "What I've typed is not a proper representation, and some things may act differently than usual" e.g. things that can take lists can no longer, due to needing to be serializable (and the least common decorator case):

"take a class, inspect a database schema and bind various internal attributes to update items in a row for that schema (somewhat common in ORMs)"

(and that is usually implemented via a subclassing of a Model class, which then in turn can implement a metaclass, to get the full mutate-class-on-creation funs, iirc)

- - -

> In particular, I don't see why mutating a type via a metaclass is preferable to using a decorator.

Its not a technical topic, its a semantics topic. while both can do whatever silliness they want, decorators are usually reserved for incidental tasks on the side, and wrapping the original function in some light filtering. Metaclasses are expected to do mutation to the class (hence requiring a metaclass), so semantically a subclass or metaclass would be more appropriate to use for this task, compared to a decorator (from the standard library, Enums come to mind as an example for this)

Re: Using attrs for everything in Python

#49

It feels a bit hampered by "bad" design decisions to me I think its safe to say that the current view of what decorators do is, a) filter things going to functions (so they error, or hit a cache), or b) register a function with another library (e.g. flask path decorator) This library does a lot more than that, so it seems that maybe a metaclass (which exists to mutate the class's creation) would be more appropriate?…

>I think its safe to say that the current view of what decorators do is, a) filter things going to functions (so they error, or hit a cache), or b) register a function with another library (e.g. flask path decorator) Why is it safe to say that? Aren't decorators just syntax for higher-order functions?

its "safe" to say that, like its also "safe" to say that will be used to denote articles in HTML

Yes, decorators can do whatever they want, but, in practical usage I'd say a majority of decorator usages do not mutate the class/function significantly from its original typed-out intent (like, they don't often add 8+ methods to a class for example, but of course they can)

not literally "safe" to say.

Re: Using attrs for everything in Python

#50
post #44

Earlier quoted context omitted.

The latest version does allow you to decorate variables with types... Not sure its doing anything with them yet.

It's not. See [1]. The retrofitting of type declarations to Python is taking a very strange path. (Evil interpretation: this is an effort by Python's little tin god to sabotage PyPy. Type information is a huge win for a compiler; it can now generate hard code for a specific type. It doesn't help CPython much, since inside CPython everything is a CObject. With type information, one could write things like NumPy, with…

How is this "sabotaging" PyPy? Also, even with type declarations, I'm not sure you could get Numpy-esque performance, given that Numpy doesn't have to dereference every element in the array.
Post reply on HN