Don't you just love writing this sort of thing :)
Arnaud Delobelle
arnodel at googlemail.com
Sat Dec 6 05:01:10 EST 2008
Lawrence D'Oliveiro <ldo at geek-central.gen.new_zealand> writes:
> In message <32cf4a79-a6e3-4250-9b5a-1ec80c748618 at j32g2000yqn.googlegroups.com>, Aaron Brady wrote:
>
>> On Dec 5, 4:32 am, Lawrence D'Oliveiro <l... at geek-
>> central.gen.new_zealand> wrote:
>>
>>> The code people write is probably a direct reflection of their thinking
>>> processes: For example, slow, plodding, one step at a time, incapable of
>>> imaginative leaps, versus those who operate directly on larger patterns
>>> at once...
>>
>> That distinction operates indirectly on smaller patterns.
>
> Do you find this
>
> (open, gzip.GzipFile)[Entry.endswith(".gz")](os.path.join(PatchesDir, Entry), "r")
>
> complicated or hard to understand?
(aside: it's funny that someone asks Aaron this quesion as he is the one
who used to post code that almost nobody understood! (although I had a
feeling there was often something interesting in it)).
in Python it is a convention only to capitalize classes, so unless Entry
and PatchesDir are classes it would be better to write them as entry and
patches_dir for example.
Why use (open, gzp.GzipFile)[Entry.endswith(".gz")] when we have had
contitional expressions for a few years now? Instead, you can write
(gzip.GzipFile if entry.endswidth(".gz") else open).
I think it will be faster (as it doesn't require the construction of a
tuple and then the retrieval of one of its elements) and clearer.
It's good to be able to understand (and I guess, to write) such code.
But to assume that others dislike it because they don't understand it
sends several wrong signals:
* you give the impression of being arrogant;
* many people will understand this code snippet perfectly easily but
they won't like it because they think that Python offers much better
ways to express the same thing.
* you seem to disregard the fact that in 'programming language' there
is the word 'language'. A language is a way to _communicate_
information, in the case of a programming language you communicate
it to the computer but also to other human beings.
To come back to your code, you could define a function like the one
below (untested). It'll allow you to add support for different
compression formats easily in the future. This is a 'pattern' which can
be useful to keep in mind and requires *some* imagination.
open_methods = { 'gz': gzip.GzipFile, 'bz2': bz2.BZ2File }
def open_by_ext(path, *args):
ext = os.path.splitext(path)[1]
return open_methods.get(ext, open)(path, *args)
Then your code snippet becomes:
open_by_ext(os.path.join(patches_dir, entry), "r")
--
Arnaud
More information about the Python-list
mailing list