One-liner lambda expressions as function decorators: (ab)using Python 3.9’s new PEP 614 feature

Photo by Andrew Le on Unsplash

Two Lambs, One Func

Photo by Matt Seymour on Unsplash
@lambda func: (lambda *para: func(*para).upper())
def greet(name):
return f'Hello, {name}!'
print(greet('Arthur Dent'))
HELLO, ARTHUR DENT!
@shout := lambda func: (lambda *para: func(*para).upper())
def greet(name):
return f'Hello, {name}!'
@shout
def reminder(name, thing):
return f'Don\'t forget your {thing}, {name}!'
print(greet('Arthur Dent'))
print(reminder('Arthur Dent', 'towel'))
HELLO, ARTHUR DENT!
DON'T FORGET YOUR TOWEL, ARTHUR DENT!

Build a Logger Cabin

Photo by Geran de Klerk on Unsplash
@lambda func: lambda *para: \
print('Func called:', func) or func(*para).upper()
def greet(name):
return f'Hello, {name}!'
print(greet('Arthur Dent'))
Func called: <function greet at 0x00000212EEFC38B0>
HELLO, ARTHUR DENT!

Once Upon a Timer

Photo by Fabrizio Verrecchia on Unsplash
import time@lambda func: lambda *para: \
[_ for _ in [ \
print('Func called:', func),
print('Start:', time.time()),
func(*para),
print('End:', time.time()),
] if _][0]
def calculate(n):
x = 0
for i in range(n):
x += i ** n
return x
print(calculate(3000))
Func called: <function calculate at 0x00000254CA9638B0>
Start: 1602050421.943357
End: 1602050422.5030253
13440703023871524924619199858289162761099130089897931730777...
import time@lambda func: lambda *para: \
list(filter(lambda _: _,[
print(f'Func called: {func}'),
(start := time.monotonic_ns()) and False,
func(*para),
(end := time.monotonic_ns()) and False,
print(f'Duration: {(end - start) / 1000000} ms')
]))[0]
def calculate(n):
x = 0
for i in range(n):
x += i ** n
return x
print(calculate(3000))
Func called: <function calculate at 0x0000024F9EE048B0>
Duration: 531.0 ms
13440703023871524924619199858289162761099130089897931730777...

Wrappering Up

Photo by Nick Bolton on Unsplash

Former translator, after-hours Maker, sunny-day analog film shooter. Currently a junior tech-book editor based in Taiwan. https://krantasblog.blogspot.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store