[Python-Dev] defaultdict proposal round three
Guido van Rossum
guido at python.org
Tue Feb 21 15:04:34 CET 2006
On 2/21/06, Fuzzyman <fuzzyman at 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/)
More information about the Python-Dev