3

our team have to snippet like below:

this:

buf = StringIO.StringIO()
gzip.GzipFile(fileobj=buf, mode='wb').write(foo)
...

and this one:

buf = StringIO.StringIO()
tmp = gzip.GzipFile(fileobj=buf, mode='wb')
tmp.write(foo)
...

which one is more pythonic?

EDITED: I have try/catch to do the error handling work, but which one is more pythonic?

dennisyuan
  • 171
  • 1
  • 10

3 Answers3

11

You need to close the GzipFile object after you are finished with it, so the one-line will not work. Instead, use a context manager expression:

buf = StringIO.StringIO()
with gzip.GzipFile(fileobj=buf, mode='wb') as tmp:
    tmp.write(foo)

The one-liner gzip.GzipFile(fileobj=buf, mode='wb').write(foo) is extremely dangerous as it depends on the GzipFile being garbage-collected at the end of the expression so that the stream is flushed. If this fails to occur (e.g. using Jython) then buf will not contain the expected result.

ecatmur
  • 152,476
  • 27
  • 293
  • 366
  • 3
    More importantly, closing the `GZipFile` instance is essential for finalizing the compression, and for writing the essential CRC value! – Martijn Pieters Jul 30 '12 at 11:30
3

Either is fine. Choose the one you find to be most readable.

Personally, I'd go with the first one, the use of the extra variable doesn't add anything for me.

That said, in this context ecatmur is correct that you need to close the GZipFile instance after writing all the data to it, as that flushes the compression data to buf and adds the gzip CRC and size information. Without this your data is potentially incomplete!

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 2
    Especially considering its extremely meaningful name. – Voo Jul 30 '12 at 11:25
  • AGREE with what ecatmur commented below. But Martijn Pieters is the ONLY people answered the question with this : "the use of the extra variable doesn't add anything for me." – dennisyuan Jul 31 '12 at 03:04
0

For example,

Man.eat.work.sleep()

Methods chaining are common in ruby/javascript, I think it's more ruby/javascript style not pythonic.

iMom0
  • 12,493
  • 3
  • 49
  • 61
  • Nope, you see it in Python too, in appropriate places. Take a look at SQLAlchemy for example, it is quite common to see chaining there as applying successive filters makes sense when working with SQL data. – Martijn Pieters Jul 30 '12 at 12:24