Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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>


This 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"


Only with decoded text. If you used encoded text through the "bytes" type, you'll get a unique value as an integer.


Id don't know when this us useful.

Also, what does `recurse()()()` mean? What are we looking for exactly?


in 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)()


Means "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."


Any scenario where it is useful to do so?


well "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.


Another fun one:

a=[]

a.append(a)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: