title: How to handle "duck typing" in Python?
body: <p>I usually want to keep my code as generic as possible. I'm currently writing a simple library and being able to use different types with my library feels extra important this time.</p>
  
  <p>One way to go is to force people to subclass an "interface" class. To me, this feels more like Java than Python and using <code>issubclass</code> in each method doesn't sound very tempting either.</p>
  
  <p>My preferred way is to use the object in good faith, but this will raise some <code>AttributeErrors</code>. I could wrap each dangerous call in a try/except block. This, too, seems kind of cumbersome:</p>
  
  <pre><code>def foo(obj):
      ...
      # it should be able to sleep
      try:
          obj.sleep()
      except AttributeError:
          # handle error
      ...
      # it should be able to wag it's tail
      try:
          obj.wag_tail()
      except AttributeError:
          # handle this error as well
  </code></pre>
  
  <p>Should I just skip the error handling and expect people to only use objects with the required methods? If I do something stupid like <code>[x**2 for x in 1234]</code> I actually get a <code>TypeError</code> and not a <code>AttributeError</code> (ints are not iterable) so there must be some type checking going on somewhere -- what if I want to do the same?</p>
  
  <p>This question will be kind of open ended, but what is the best way to handle the above problem in a clean way? Are there any established best practices? How is the iterable "type checking" above, for example, implemented?</p>
  
  <h2>Edit</h2>
  
  <p>While <code>AttributeError</code>s are fine, the <code>TypeErrors</code> raised by native functions usually give more information about how to solve the errors. Take this for example:</p>
  
  <pre><code>&gt;&gt;&gt; ['a', 1].sort()
  Traceback (most recent call last):
    File "&lt;stdin&gt;", line 1, in &lt;module&gt;
  TypeError: unorderable types: int() &lt; str()
  </code></pre>
  
  <p>I'd like my library to be as helpful as possible.</p>