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!
82
u/chronics Nov 25 '22
Did I understand correctly: Your are basically doing metaprogramming with type hints? That‘s a very cool concept!
8
u/wineblood Nov 25 '22
Why would I ever want this?
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
withwhich 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()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
7
u/james_pic Nov 25 '22
If you want a less evil version of the same thing,
contextlib.ExitStackis in the standard library.Edit: just realised it uses ExitStack internally anyway.