title: Is it Pythonic to check function argument types?
body: <p>I know, type checking function arguments is generally frowned upon in Python, but I think I've come up with a situation where it makes sense to do so. </p>
  
  <p>In my project I have an Abstract Base Class <code>Coord</code>, with a subclass <code>Vector</code>, which has more features like rotation, changing magnitude, etc. Lists and tuples of numbers will also return True for <code>isinstance(x, Coord).</code> I also have many functions and methods that accept these Coord types as arguments. I've set up decorators to check the arguments of these methods. Here is a simplified version:</p>
  
  <pre><code>class accepts(object):
      def __init__(self, *types):
          self.types = types
  
      def __call__(self, func):
          def wrapper(*args):
              for i in len(args):
                  if not isinstance(args[i], self.types[i]):
                      raise TypeError
  
              return func(*args)
  
          return wrapper
  </code></pre>
  
  <p>This version is very simple, it still has some bugs. It's just there to illustrate the point. And it would be used like:</p>
  
  <pre><code>@accepts(numbers.Number, numbers.Number)
  def add(x, y):
      return x + y
  </code></pre>
  
  <p>Note: I'm only checking argument types against Abstract Base Classes.</p>
  
  <p>Is this a good idea? Is there a better way to do it without having to repeat similar code in every method?</p>
  
  <p><strong>Edit:</strong></p>
  
  <p>What if I were to do the same thing, but instead of checking the types beforehand in the decorator, I catch the exceptions in the decorator:</p>
  
  <pre><code>class accepts(object):
      def __init__(self, *types):
          self.types = types
  
      def __call__(self, func):
          def wrapper(*args):
  
              try:
                  return func(*args)
              except TypeError:
                  raise TypeError, message
              except AttributeError:
                  raise AttributeError, message
  
          return wrapper
  </code></pre>
  
  <p>Is that any better?</p>