#๐ why does this work? it shouldn't ๐๐ญ
21 messages ยท Page 1 of 1 (latest)
@rare geyser
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.
What's wrong with this?
that's not cursed
functions that return functions are used in tons of places
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
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
!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"))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
[{'id': 10, 'name': 'alice', 'grade': 5}, {'id': 5, 'name': 'bob', 'grade': 2}, {'id': 2, 'name': 'charlie', 'grade': 7}, {'id': 11, 'name': 'denise', 'grade': 5}]
Returning a lambda is more niche, but it can be useful in some cases
https://github.com/networkx/networkx/blob/networkx-3.4.2/networkx/classes/filters.py#L26-L53
Returning a closure defined with def, on the other hand, is extremely common. That's how most decorators are implemented in libraries
ok this one makes actually perfect sense, thanks
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.