![](https://secure.gravatar.com/avatar/047f2332cde3730f1ed661eebb0c5686.jpg?s=120&d=mm&r=g)
On 2/21/06, Fuzzyman <fuzzyman@voidspace.org.uk> wrote:
I've had problems in code that needs to treat strings, lists and dictionaries differently (assigning values to a container where all three need different handling) and telling the difference but allowing duck typing is *problematic*.
Consider designing APIs that don't require you to mae that kind of distinction, if you're worried about edge cases and classifying arbitrary other objects correctly. It's totally possible to create an object that behaves like a hybrid of a string and a dict. If you're only interested in classifying the three specific built-ins you mention, I'd check for the presense of certain attributes: hasattr(x, "lower") -> x is a string of some kind; hasattr(x, "sort") -> x is a list; hasattr(x, "update") -> x is a dict. Also, hasattr(x, "union") -> x is a set; hasattr(x, "readline") -> x is a file. That's duck typing! -- --Guido van Rossum (home page: http://www.python.org/~guido/)