pythonic way to return object based on parameter type
<p>I have a simple class that can operate on a variety of base classes (strings, list, file... handed to it in Python3.x and return the same type. For now, I am using <code>isinstance</code> for type checking though have read all the admonishments of doing so.</p>

<p>My question is what is the pythonic way of writing this function. 'Duck typing' seems more appropriate for testing that the correct type was used. I considered overloading with passing type <code>[func(type, input)]</code> or testing for <code>hasattr</code>. I want the code to be consistent with best practices, future friendly and up-gradable by a programmer other than myself. </p>

<p>Rather than checking the actual <em>type</em> of the object, you should check the <em>behavior</em> of the object.</p>

<p>What I mean by that is rather than</p>

<pre><code>isinstance(foo, str) or isinstance(foo, list) or ...
</code></pre>

<p>You are more interested in whether it is a sequence, meaning it has defined <code>__iter__</code> for example</p>

<pre><code>hasattr(foo, '__iter__')
</code></pre>

<p>In this sense you don't really care what the object is per se, rather you just want the objects to behave a certain way.</p>

<p>Similarly if you wanted the objects to be "index-able" you could check </p>

<pre><code>hasattr(foo, '__getitem__')
</code></pre>

<p>You could follow this pattern to enforce your "duck typing" design.</p>

python