FUN_POSTING: calling a function enclosed in a variable

Did you know you can enclose a function in a variable, and call it from that variable?
Check this out, all these statements print the greeting:

# from list:
[print][0]('ahoj')
# or:
[print].pop()('ahoj') 
# from tuple:
(print,)[0]('ahoj')
# from dictionary:
{ 'a': print }['a']('ahoj')
# or
{ 'a': print }.get('a')('ahoj')
# even from a lambda function:
(lambda : print)()('ahoj')

Level 2:
Now let’s try to use the itemgetter !

from operator import itemgetter
itemgetter(0)([print])('ahoj') # list
itemgetter(0)((print,))('ahoj') # tuple
itemgetter('a')({'a': print})('ahoj') # dictionary

It works!
Happy coding :slight_smile:
MK

1 Like

with a little bit of hack, you can also enclose functions in parentheses,
so that instead of:

print(list(range(5)))

one can write:

(print)((list)((range)(5)))

which gives the same output.
:wink:

1 Like

In programming language design, this is referred to as having “first-class functions.” Here’s some more related reading on them:

1 Like

ways of printing hello world,
this is nice:

t = (print,'hello','world')
t[0](t[1],t[2])