News for hackers. Stuff that matters.
Re:Please fix your Python decorators by lotsoflumens on Monday August 01, 2016 @03:45PM (#12205300)
Is it just me, or isn't it obvious now that decorators are, at best, an anti-pattern, or worse, a misguided attempt at code obfuscation?
Re:Please fix your Python decorators by mmierz on Monday August 01, 2016 @04:45PM (#12205788)
It's not obvious to me. Example use case:

The last time I wrote a bunch of decorators, I was writing python bindings to a set of C++ classes that each had an internal error state that had to be checked after each time a method was called to see if the method failed. If the error state was set, then subsequent method calls for the same object would fail silently, so it was crucial that the error state be checked. There were dozens of methods per class.

I ended up writing a class decorator that would decorate each method with the appropriate method decorator. The method decorator would call the GetErrorCode method, check if nonzero, reset the error state of the object, and then raise an appropriate python exception if necessary.

Major surgery to change the error handling in the called C++ code was not an option.

Can you suggest a better approach?

Re:Please fix your Python decorators by jdmichal on Monday August 01, 2016 @05:52PM (#12206337)
Define a function to do the same and call that at the end of every method? These don't seem that different to me:

    def doStuff():
        # do stuff
        return checkError(value)

    @checkError
    def doStuff():
        # do stuff
        return value
EDIT: In fact, I think the above succinctly hits on lotsoflumens' point. The latter clearly obfuscates the fact that an error check is performed behind the decorator. The former makes it very clear that something is happening to the return value before it leaves.
Re:Please fix your Python decorators by jerf on Monday August 01, 2016 @10:07PM (#12207424)
I think the antipattern is examining a function's textual arguments and trying to infer things from the names and such. I've had more trouble with that than it has saved me time, between not being able to diagnose things when the magic breaks and the sheer opacity of where arguments are coming from, not to mention all the other quirky little things that go wrong when you push a system that hard.

Just because you can introspect a thing does not mean you must introspect that thing.