On Sun, 12 Sep 2010 04:01:39 am Walter Prins wrote: > I guess the question to ask/consider is: How can be establish whether > a particular object supports a particular interface/set of behaviours > that we require? E.g. how do we most pythonically check whether some > object "walks like a list" and "quacks like a list" without tying > such code to explicit type checking?
isinstance(object, base_class) becomes even more useful in Python 2.6 and beyond, because when you create a class, you can register it as a list even if you didn't inherit from list. You're essentially promising "this class will walk and quack and swim like a list". But often you don't care that something walks, quacks, and swims like a list. You might only care that it walks. We can combine "Look Before You Leap" with duck-typing: def swap_items(sequence): try: sequence[0] = sequence[0] except Exception: print("does not support item lookup or item assignment") else: for i in range(0, len(sequence)-1, 2): sequence[i], sequence[i+1] = sequence[i+1], sequence[i] return sequence >>> swap_items("abcd") does not support item lookup or item assignment >>> swap_items(['a', 'b', 'c', 'd', 'e', 'f']) ['b', 'a', 'd', 'c', 'f', 'e'] -- Steven D'Aprano _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor