Search code examples
pythonlambdasyntaxdecorator

How to use a lambda expression in a decorator?


I found this piece of interesting code online, however it throws a syntax error. How can I fix it?

@lambda _: _()
class _:
    def __format__(_, __):
        _.__class__._ = property(lambda _: print(__))
        return ""
def __() -> f"{_: Hello, world!}": ...
_._

Error:

  File "<ipython-input-17-773eeacca942>", line 1
    @lambda _: _()
          ^
SyntaxError: invalid syntax

Solution

  • This piece of code works with Python version 3.9+. After running it with the newer python versions, the output will be Hello World!.

    You can find a detailed description of how and why the code works in this article: https://mathspp.com/blog/the-most-obscure-hello-world-program