On 1/16/07, Ben Finney <[EMAIL PROTECTED]> wrote: > "BJörn Lindqvist" <[EMAIL PROTECTED]> writes: > > > import rational > > rational.rational(45) > > rational.rational(45.0) > > rational.rational([45, 45.5]) > > > > def rational(obj): > > initers = [(int, from_int), (basestring, from_str), (list, from_list)] > > for obj_type, initer in initers: > > if isinstance(obj, obj_type): > > return initer(obj) > > raise ValueError("Can not create a rational from a %r" % > > type(obj).__name__) > > You've just broken polymorphism. I can't use your factory function > with an instance of my custom type that behaves like a list, but is > not derived from list (or a non-'int' int, or a non-'basestring' > string).
Indeed, but I do not think that is fatal. There are many functions in Pythons stdlib that breaks duck typing exactly like that. > Use the supplied value as you expect to be able to use it, and catch > the exception (somewhere) if it doesn't work. That will allow *any* > type that exhibits the correct behaviour, without needlessly > restricting it to a particular inheritance. Can you show an example of that? It seems like that approach would lead to some very convoluted code. -- mvh Björn -- http://mail.python.org/mailman/listinfo/python-list