3 ms·
Here's a neat bit of Python abuse I stumbled across recently... you can define a method to return itself: >>> def recurse(): ... return recurse .
by bcbrown 9y ago
Here's a neat bit of Python abuse I stumbled across recently... you can define a method to return itself:
>>> def recurse():
... return recurse
...
>>> recurse
<function recurse at 0x1083b5f28>
>>> recurse()
<function recurse at 0x1083b5f28>
>>> recurse()()()
<function recurse at 0x1083b5f28>
- falcor84 9y agoThis is cool :) Reminds me of the fact that Python doesn't have a char type and it's strings all the way down: "a"[0][0][0][0] == "a"
- sametmax 9y agoOnly with decoded text. If you used encoded text through the "bytes" type, you'll get a unique value as an integer.
- abhishekjha 9y agoId don't know when this us useful. Also, what does `recurse()()()` mean? What are we looking for exactly?
- dagw 9y agoin general `f()()` means call the function returned by f() with no arguments. So f()()() means call the function returned by f()() with no arguments. In this case recurse() returns itself so recurse == recurse()()()()... It's more of an interesting observation than anything useful The syntax can occasionally be useful if you have a function the generates function, but then you'd be calling initial function with some argument like this: f_x = f(x)() f_y = f(y)()
- y4mi 9y agowell "recurse" returns an object, "()" executes the returned object. As that execution returns an executeable object as well, you can just start to chain the "()"s ad infinitum. its just abusing a core mechanic.
- fwdpropaganda 9y agoMeans "take the function recurse, execute it, then take the thing it returns and execute that, and then take the thing that returns and execute that."
- abhishekjha 9y agoAny scenario where it is useful to do so?
- onnoonno 9y agoAnother fun one: a=[] a.append(a)