title: A python function that accepts as an argument either a scalar or a numpy array
body: <p>As the title says, suppose I want to write a sign function (let's forget sign(0) for now), obviously we expect sign(2) = 1 and sign(array([-2,-2,2])) = array([-1,-1,1]). The following function won't work however, because it can't handle numpy arrays.</p>
  
  <pre><code>def sign(x):
      if x&gt;0: return 1
      else: return -1
  </code></pre>
  
  <p>The next function won't work either since x doesn't have a shape member if it's just a single number. Even if some trick like y = x*0 + 1 is used, y won't have a [] method.</p>
  
  <pre><code>def sign(x):
      y = ones(x.shape)
      y[x&lt;0] = -1
      return y
  </code></pre>
  
  <p>Even with the idea from another question(<a href="https://stackoverflow.com/questions/12653120/how-can-i-make-a-numpy-function-that-accepts-a-numpy-array-an-iterable-or-a-sc">how can I make a numpy function that accepts a numpy array, an iterable, or a scalar?</a>), the next function won't work when x is a single number because in this case x.shape and y.shape are just () and indexing y is illegal.</p>
  
  <pre><code>def sign(x):
      x = asarray(x)
      y = ones(x.shape)
      y[x&lt;0] = -1
      return y
  </code></pre>
  
  <p>The only solution seems to be that first decide if x is an array or a number, but I want to know if there is something better. Writing branchy code would be cumbersome if you have lots of small functions like this.</p>