4 ms·
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
by francoisdevlin 14y ago
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.
- jamesgeck0 14y agoI agree that this doesn't fit Python well, but why was it bad in Ruby?
- francoisdevlin 14y agoBecause of non local returns. People abuse them when instead they should be using an exception, or preprocessing their data better.
- stcredzero 14y agoBlocks 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.
- sirclueless 14y agoNested 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); };
- stcredzero 14y agoThat'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?