#๐Ÿ”’ why does this work? it shouldn't ๐Ÿ˜”๐Ÿ˜ญ

21 messages ยท Page 1 of 1 (latest)

rare geyser
#

does anyone have more of these cursed python examples?

pliant elmBOT
#

@rare geyser

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

rare geyser
#

like... it actually works though and that even in 3.6

#

๐Ÿ™๐Ÿ™

sterile vigil
#

that's not cursed

junior hare
#

functions that return functions are used in tons of places

rare geyser
#

what how would that be useful?

#

outer()(2) is the exact same as

def outer(x): return x**2
outer(2)```
just that one defines an unnecessary lambda and needs extra parenthesis
junior hare
#

You could do like a closure

#

or something

#
def make_multiplier(multiplier):
    def multiplier_function(x):
        return x * multiplier
    return multiplier_function

double = make_multiplier(2)
triple = make_multiplier(3)

print(double(4))  # 8
print(triple(4))  # 12
#

like that

#

You could also do like a logger or something

sterile vigil
# rare geyser outer()(2) is the exact same as ```py def outer(x): return x**2 outer(2)``` just...

!e
Functions that capture variables from the outer scope ("closures") are very useful. For example:

my_students = [
    {"id": 2, "name": "charlie", "grade": 7},
    {"id": 10, "name": "alice", "grade": 5},
    {"id": 11, "name": "denise", "grade": 5},
    {"id": 5, "name": "bob", "grade": 2},
]

def sort_by_grade(students, field):
    if field not in {"name", "grade"}:
        raise KeyError("Can only sort by name and grade")
    return sorted(students, key=lambda s: (s[field], s["id"]))

print(sort_by_grade(my_students, "name"))
pliant elmBOT
sterile vigil
#

Returning a closure defined with def, on the other hand, is extremely common. That's how most decorators are implemented in libraries

rare geyser
pliant elmBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.