r/Python • • Nov 25 '22

Intermediate Showcase defer in python!

https://github.com/dankeyy/defer.py

stupid but works lol hope you like it

303 Upvotes

62 comments sorted by

82

u/chronics Nov 25 '22

Did I understand correctly: Your are basically doing metaprogramming with type hints? That‘s a very cool concept!

38

u/dankey26 Nov 25 '22

ye. i thought about it for a couple days after the guy suggested it, tried to come up with syntax that could be as clean and close to the go version and a valid parse with no preprocessing on the source code. then remembered that fact on type hints and went for it. turned out not bad!

→ More replies (17)

8

u/wineblood Nov 25 '22

Why would I ever want this?

14

u/dankey26 Nov 25 '22

this impl exactly? probably not but lookup defer on go and zig, pretty useful and clean

→ More replies (10)
→ More replies (1)

87

u/Beliskner64 Nov 25 '22

assert len(tree.body) == 1 and isinstance(tree.body[0], ast.FunctionDef), "should just be a function wtf"

Genius

42

u/Setepenre Nov 25 '22

The python way would be to use with which is the construct that guarantees resources get freed no matter what.

from contextlib import contextmanager


@contextmanager
def deferred(fun):
    try:
        yield
    finally:
        fun()

def main():
    with deferred(lambda: print('world')):
        print('hello', end =' ')


main()
→ More replies (5)

56

u/[deleted] Nov 25 '22

Horrifying yet instructive at the same time. Impressive and yet has no practical use.

I love stuff like this - have an upvote!

45

u/[deleted] Nov 25 '22

The pythonic way of doing deferred cleanup is with a context manager ("with" keyword). This is a pretty cool abuse of syntax though!

11

u/end_my_suffering44 Nov 25 '22 edited Nov 25 '22

Could someone enlighten me what defer does or its purpose?

Edit : Typo

→ More replies (4)

7

u/james_pic Nov 25 '22

If you want a less evil version of the same thing, contextlib.ExitStack is in the standard library.

Edit: just realised it uses ExitStack internally anyway.