Skip to content

Instantly share code, notes, and snippets.

@GroomedGorilla
Last active March 10, 2023 19:53
Show Gist options
  • Save GroomedGorilla/1c61c0c14a4e3d3e6766ff49174e94dd to your computer and use it in GitHub Desktop.
Save GroomedGorilla/1c61c0c14a4e3d3e6766ff49174e94dd to your computer and use it in GitHub Desktop.
Anonymous vs Named Functions Bytecode comparison
# Summing via Anonymous Function
import dis
dis.dis(lambda x, y: x+y)
# output - using Python v.3.10.2
1 0 LOAD_FAST 0 (x)
2 LOAD_FAST 1 (y)
4 BINARY_ADD
6 RETURN_VALUE
# Summing via Named Function
import dis
def add(x, y):
return x + y
dis.dis(add)
# output - using Python v.3.10.2
2 0 LOAD_FAST 0 (x)
2 LOAD_FAST 1 (y)
4 BINARY_ADD
6 RETURN_VALUE
@lambda func: (lambda *phrase_input: func(*phrase_input).upper())
def louder(phrase):
return f"Did you say '{phrase}'?"
louder("fizz, buzz")
# output
"DID YOU SAY 'FIZZ, BUZZ'?"
factorial = (lambda f: lambda n: 1 if n == 0 else n * f(f)(n-1))(
lambda f: lambda n: 1 if n == 0 else n * f(f)(n-1)
)
factorial(6)
# or, anonymously as
(lambda f: lambda n: 1 if n == 0 else n * f(f)(n-1))(lambda f: lambda n: 1 if n == 0 else n * f(f)(n-1))(6)
# output
720
# maps the lambda over the collection `numbers` returning a list
# containing the remainders of each number divided by 2
list(map(lambda x : x%2, numbers))
# filters through `numbers` returning a list of only numbers
# non-divisible by 2
list(filter(lambda x: x % 2 != 0, numbers))
(lambda x: print("double:", x*2) or print("triple:", x*3) or print("square:", x*x))(5)
# output
double: 10
triple: 15
square: 25
(lambda x: x*2 or x*x or x+6)(5)
# output
10
people = [
{"name": "Gillian", "age": 25},
{"name": "Jeffrey", "age": 30},
{"name": "Jessica", "age": 20},
]
people.sort(key=lambda x: (x["age"], x["name"]))
# output
[{'name': 'Jessica', 'age': 20}, {'name': 'Gillian', 'age': 25}, {'name': 'Jeffrey', 'age': 30}]
@scream := lambda func: (lambda *phrase_input: func(*phrase_input).upper())
def louder(phrase):
return f"Did you say '{phrase}'?"
@scream
def hello(name):
return f"Hello {name}. Is it me you're looking for?"
hello("Jeff")
# output
"HELLO JEFF. IS IT ME YOU'RE LOOKING FOR?"
d = {1: 4, 2: 2, 3: 3, 4: 1}
sorted(d.items(), key=lambda x: x[1])
# output
[(4, 1), (2, 2), (3, 3), (1, 4)]
upper = lambda x: x.upper()
upper((lambda y : y + ",buzzzz")("fizzzz"))
# or joining it all in one anonymous line
(lambda x: x.upper())((lambda y : y + ",buzzzz")("fizzzz"))
# output
'FIZZZZ,BUZZZZ'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment