by yummyfajitas · 14y ago · 0 comments
In [ x.y() for x in X], it's immediately obvious that x.y() is doing some work. Not so obvious in [ x.y for x in X ].
This is a very practical concern - in Django code (both mine and other people's), I see lots of unnecessary SQL queries all over the place because of this.
Of course, Ruby, Scala, etc, are not immune to this criticism.
Python is different because the style guide explicitly discourages [1] computationally expensive accessor methods (as well as accessor methods with side effects) specifically so that programmers can treat accessor methods the same way they would treat a data field. Assuming that x.y is a field access in Python is not supposed to lead to problems, and if it does, it's the fault of the class implementer and not the user.
[1] http://www.python.org/dev/peps/pep-0008/#designing-for-inher...
http://en.wikipedia.org/wiki/Uniform_access_principle
It does put more onus on the API implementer to be careful about hiding non-trivial work, like you say.
The issue being that attributes can be accessed at all of course.
> Of course, Ruby, Scala, etc, are not immune to this criticism.
Well they are — or at least Ruby is — in that they don't allow attribute accesses from third-parties at all. Just consider that Python is the same (it is).
Hell, in Python `.` is already a method call. In fact it's a whole sequence of method calls.
Yes it is - that's always a method call: http://docs.python.org/reference/datamodel.html#invoking-des...
The problem is that you're unclear whether it's a mutating method or not, as well as whether it's an expensive operation. But that can be solved a number of ways - immutability and lazy evaluation would be one approach, though unfortunately neither Python nor Ruby enforces immutability, and both use absurdly eager evaluation.
(Regarding that last point, try doing [x.y() for x in foo][0] and you'll see that y is called for every x!)