title: Writing functions that accept both 1-D and 2-D numpy arrays?
body: <p>My understanding is that 1-D arrays in numpy can be interpreted as either a column-oriented vector or a row-oriented vector.  For instance, a 1-D array with shape <code>(8,)</code> can be viewed as a 2-D array of shape <code>(1,8)</code> or shape <code>(8,1)</code> depending on context.</p>
  
  <p>The problem I'm having is that the functions I write to manipulate arrays tend to generalize well in the 2-D case to handle both vectors and matrices, but not so well in the 1-D case.</p>
  
  <p>As such, my functions end up doing something like this:</p>
  
  <pre><code>if arr.ndim == 1:
      # Do it this way
  else:
      # Do it that way
  </code></pre>
  
  <p>Or even this:</p>
  
  <pre><code># Reshape the 1-D array to a 2-D array
  if arr.ndim == 1:
      arr = arr.reshape((1, arr.shape[0]))
  
  # ... Do it the 2-D way ...
  </code></pre>
  
  <p>That is, I find I can generalize code to handle 2-D cases <code>(r,1)</code>, <code>(1,c)</code>, <code>(r,c)</code>, but not the 1-D cases without branching or reshaping.</p>
  
  <p>It gets even uglier when the function operates on multiple arrays as I would check and convert each argument.</p>
  
  <p>So my question is: am I missing some better idiom?  Is the pattern I've described above common to numpy code?</p>
  
  <p>Also, as a related matter of API design principles, if the caller passes a 1-D array to some function that returns a new array, and the return value is also a vector, is it common practice to reshape a 2-D vector <code>(r,1)</code> or <code>(1,c)</code> back to a 1-D array or simply document that the function returns a 2-D array regardless?</p>
  
  <p>Thanks</p>