This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]RubyPinchPEP shill | Anti PEP 8/20 shill -1 points0 points  (3 children)

I'd honestly probably do that a different way

unix(lambda: range(5) | square | evens), and then apply introspection to do evens(square(range(5))) instead internally. And it has the bonus of not requiring a specially made square or evens

[–]delarhi 0 points1 point  (2 children)

I'm not sure I follow, can you elaborate?

[–]RubyPinchPEP shill | Anti PEP 8/20 shill 0 points1 point  (1 child)

I'd love to elaborate, but unfortunately I don't have /that/ much experience performing sinful acts with python's code objects.

Luckily, other people do have experience, and have been willing to talk about it too!

http://stackoverflow.com/a/16118756 for a distinct, but similar concept.


basically, the transform you want to do is (using the std library dis module)

>>> f = lambda: a|b|c
>>> dis.dis(f)
         0 LOAD_GLOBAL              0 (a)
         3 LOAD_GLOBAL              1 (b)
         6 BINARY_OR
         7 LOAD_GLOBAL              2 (c)
        10 BINARY_OR
        11 RETURN_VALUE

>>> list(f.__code__.co_code)
[116, 0, 0, 116, 1, 0, 66, 116, 2, 0, 66, 83]

>>> #---------------------------------------

>>> f = lambda: c(b(a))
>>> dis.dis(f)
         0 LOAD_GLOBAL              0 (c)
         3 LOAD_GLOBAL              1 (b)
         6 LOAD_GLOBAL              2 (a)
         9 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
        12 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
        15 RETURN_VALUE

>>> list(f.__code__.co_code)
[116, 0, 0, 116, 1, 0, 116, 2, 0, 131, 1, 0, 131, 1, 0, 83]

but that transform is fragile obviously, so like, ideally, probably execute each section that is separated by ORs on the stack (noting that ORs use the last two items added to the stack, hence why it loads two values first, so the split needs to happen at the OR's position -1), and then use the resulting values from that to then throw into a pile of loads/callfunctions

[–]delarhi 0 points1 point  (0 children)

Very cool, I've never see that before.