質問

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?

役に立ちましたか?

解決

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!

他のヒント

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.

For example,

Man.eat.work.sleep()

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top