1
\$\begingroup\$

Background

  • Python (version 2.7.2)

Problem

  • You want to specify an array in your code.
  • You want to use the 'syntax sugar' available in Ruby and Perl.
  • You are a fanatic about readable code but also saving keystrokes.

Solution

  • Python Triple-quoted string
  • Python splitlines
  • Python list comprehension

Pitfalls

  • The solution may look ugly or un-Python-ish

Question

Are there any refactorings, suggestions or comments on this approach?

### ********************
## setup an array using append
ary_names = []
ary_names.append('alpha')
ary_names.append('bravo')
ary_names.append('charlie')
ary_names.append('delta')
ary_names.append('echo')

### ********************
## setup an array using triple-quoted string
ary_names = [
  item.strip() for item in  
  """

  alpha
  bravo
  charlie
  delta
  echo

  """
  .splitlines()
  if(not item.strip()=='')
]

"""
Here is a ruby example for comparison

ary_names = %w[
  alpha
  bravo
  charlie
  delta
  echo      
]
"""
\$\endgroup\$
5
\$\begingroup\$

If you call split with no arguments, it will split on any whitespace and drop any empty elements. Knowing that, it's as simple as this:

ary_names = """
    alpha
    bravo
    charlie
    delta
    echo
""".split()

If you have only five short elements, you may want to put them all on one line:

ary_names = 'alpha bravo charlie delta echo'.split()

Of course, you'd only want to do that if it fits easily on one line.

\$\endgroup\$
  • 3
    \$\begingroup\$ its worth noting this won't worth string tokens including multiple words, unlike OP's answerr \$\endgroup\$ – theodox Sep 6 '13 at 15:28
3
\$\begingroup\$

This will work as written. You could shorten it slightly by replacing

if(not item.strip()=='')

with

 if item.strip()

You're also calling strip twice, you could skip that with:

array_names = [i for i in map(str.strip, my_big_string.splitlines()) if i]

I would avoid inlining the actual constants in the list comprehension tool - that's bad for readability if it's not sitting on the outermost outline level.

On the philosophical level, I'm ambivalent. I hate all the quotes etc too, but this only works for strings, so it's not a general purpose idiom. You could extend it with exec or eval to get non-string values, but that's a whole big can o' worms :)

\$\endgroup\$
  • 2
    \$\begingroup\$ strip isn't a top-level function; you'd have to use str.strip or lambda s: s.strip() if you want to pass it to map. \$\endgroup\$ – icktoofay Sep 6 '13 at 5:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.