12

I have a long function, as seen below:

hash_correct = hashlib.md5(salt + password)).digest().encode("base64")

I'd like to split it up into two lines but am not sure of the correct way to do this in Python?

Thanks.

ensnare
  • 40,069
  • 64
  • 158
  • 224

2 Answers2

21

The coding guidelines limiting length of lines is there, in part, to make the code more readable. In your case of chained method calls, the meaning is not clear. You should pick some temporary variable names for the intermediate values so that a reader of the code can understand the chain easily.

One example might be:

safe_md5 = hashlib.md5(salt + password)
crypto_hash = safe_md5.digest()
hash_correct = crypto_hash.encode('base64')

This leads the reader down a garden path to understanding. Very little is lost in performance, and the additional code is all added for purpose.

Charles Merriam
  • 19,908
  • 6
  • 73
  • 83
  • I think you're missing an invocation on the `.digest` function, but other than that, very good answer. – bcherry Mar 31 '10 at 04:25
  • little lost in *runtime* performance, maybe but not having any scope operator all those intermediate variables will live for the duration of the function, if they happen to need large memory, all the worse. – dashesy Jan 24 '14 at 00:00
3

Prefer Charles Merram's answer, but I thought this worth noting as working but ugly and to be discouraged. Because '.' is a lexical delimiter, the following worked:

>>> 'abc def' . split()
['abc', 'def']
>>> 'abc def' . \
... split()
['abc', 'def']
>>> sys.version
'2.6.4 (r264:75706, Dec  7 2009, 18:45:15) \n[GCC 4.4.1]'

but don't do that.

msw
  • 42,753
  • 9
  • 87
  • 112