|
|
|
|
|
by sirclueless
5169 days ago
|
|
Nested functions can access variables from local scope in Python, so this isn't a huge issue. It's a bit wonky in python (see discussion of the nonlocal keyword, Python did this wrong from the start) but it solves your encapsulation problem. def sorted_by(xs, attr):
def cmp_attr(a, b):
return cmp(getattr(a, attr), getattr(b, attr))
return sorted(xs, cmp_attr)
It takes a little more vertical space and requires you to give a name to something that might otherwise be anonymous, but in the long term it's actually beneficial in my opinion. I've actually taken to using the same pattern in my JavaScript development, giving all of my callbacks names, because it makes maintenance so much easier later. var load_into = function (url, elem) {
var handle_response = function (response) {
$(elem).html(response);
};
$.get(url, handle_response);
};
|
|