A post about how this community’s banner used the python 2 print syntax - print "Hello World" - made me question, can we print a hello world message in Python 3 without using parentheses?

It turned out to be sort of a fun challenge, I’ve found 3 different approaches that work. I’d be interested to see what you come up with! (it seems I can’t put spoilers in Lemmy, so I won’t share my solutions yet in case y’all want to have a go).

Edit: Posted my solutions in the comments

  • @[email protected]OP
    link
    fedilink
    71 year ago

    Alright, here are my solutions :)

    1. Import Easter egg
    import __hello__
    

    Not the most technically interesting, but a fun Easter egg!

    1. Class decorators
    @print
    @lambda _: "Hello World"
    class Foo: 
        ...
    

    Decorators are another way of calling a function, so can be abused to solve this task. You need to decorate a class rather than a function though, since a function definition requires parentheses!

    1. Dunder methods
    class Printer:
        __class_getitem__ = print
    
    Printer["Hello World"]
    

    There might be some other Dunder methods you can use to do this, although it’s sort of difficult since most (e.g. __add__) only describe behaviour on the instance of the class.

    1. More dunder methods
    from _sitebuiltins import Quitter
    Quitter.__add__ = print
    exit + "Hello World"
    

    Writing number 3 made me realise I just needed to find a class that already had an instance and change that. I’m sure there are many other cases of this, but here’s one!

    • @[email protected]
      link
      fedilink
      11 year ago

      Very interesting solutions. I was in the direction of using dunder methods but could not figure out how. Haven’t heard of the __class_getitem__. The second solution is especially inspiring.