[TIP] alphabetical order in testing
sienkiew at stsci.edu
Thu Jan 21 07:11:19 PST 2010
holger krekel wrote:
> On Wed, Jan 20, 2010 at 17:09 -0500, Mark Sienkiewicz wrote:
>> In that case, there is some clever python feature that I don't know
>> about. How does it work? Is it easier than
>> import os
>> l = dir(os)
> functions have a bytecode object which has a co_firstlineno line
> number - you can use that to sort. If you insist on oneliners:
> sorted(vars(os).items(), key=lambda x:
> getattr(getattr(x, 'func_code', None), 'co_firstlineno', 0))
> In practise i'd rather write this as a five-liner.
No, I don't insist on one-liners. I agree: if I were to write
something like this (which I can do now that I know how) I would write
it as about 5 lines of code and another 5 lines of comments explaining
how it works. I'm not a fan of taking 5 simple lines and cramming them
into 1 complicated line.
But this example points out a general philosophical difference that I
think would be useful to the group:
I consider "l = dir(os)" to be simpler for two reasons. The LESS
important reason is that it contains a single function call.
The more important reason is:
You can hardly learn python without being aware of dir(); If I asked any
random python programmer "How do you get a list of the symbols in a
module, sorted alphabetically?" I would expect the answer "l = dir(mod)"
or maybe "l = dir(mod); l.sort()". That is easy for just about anybody
who can write python.
For comparison, I've been using python for years, and I have never seen
documentation for the interface in this example. (I don't claim that it
is undocumented -- just that I have never seen it, and after flipping
through the table of contents of the standard library, it is not obvious
to me where to look for it.) If I don't know about it, then my first
task is to ask "how would I find this information?", which would mean
searching the documentation, then possibly reverse engineering the
python interpreter if I did not find anything useful. Compare with just
a few seconds to write code that uses dir().
So in a way, we're both right, in slightly different domains: Listing
the functions alphabetically is easy, for just about anybody. Listing
the functions by line number is easy, for anybody who knows about this
Of course, there is no "rule of programming" that falls out of this
observation. It's just something that we should all be aware of.
More information about the testing-in-python