Re:Code blocks in Python
by francoisdevlin on Friday April 20, 2012 @09:03AM
(#3867668)
This is a terrible idea, and ruby used the wrong implementation. If you want this behaviour, you should just define a higher order function/decorator, and put your "block" in its own function. This is a case where there should be only one way to do it.
[ Parent
| on HN ]
Re:Code blocks in Python
by stcredzero on Friday April 20, 2012 @09:42AM
(#3867823)
Blocks in other languages can help maintain encapsulation, if they can access variables from their local scope. They can also enable programmers to write their own control structures which look like natural first class control structures in the host language. I don't see this as a natural way of doing either.
Re:Code blocks in Python
by sirclueless on Friday April 20, 2012 @12:22PM
(#3868531)
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);
};
Re:Code blocks in Python
by stcredzero on Friday April 20, 2012 @01:10PM
(#3868782)
That's not bad. I agree named functions are fine for many solutions for maintaining encapsulation. They're not that great for writing your own control structures. How would you implement my ifTrue:ifFalse:ifMaybe: example?
Re:Code blocks in Python
by jamesgeck0 on Friday April 20, 2012 @09:33AM
(#3867779)
I agree that this doesn't fit Python well, but why was it bad in Ruby?
Re:Code blocks in Python
by francoisdevlin on Friday April 20, 2012 @10:32AM
(#3868015)
Because of non local returns. People abuse them when instead they should be using an exception, or preprocessing their data better.