On 06/08/2013 11:07, Rui Maciel wrote:
Joshua Landau wrote:

Unless you have a very good reason, don't do this [i.e. checking
arguments for type at runtime and raising TypeError]. It's a damn pain
when functions won't accept my custom types with equivalent
functionality -- Python's a duck-typed language and it should behave
like one.

In that case what's the pythonic way to deal with standard cases like this
one?

<code>
class SomeModel(object):
         def __init__(self):
                 self.label = "this is a label attribute"

         def accept(self, visitor):
                 visitor.visit(self)
                 print("visited: ", self.label)


class AbstractVisitor(object):
         def visit(self, element):
                 pass


class ConcreteVisitorA(AbstractVisitor):
         def visit(self, element):
                 element.label = "ConcreteVisitorA operated on this model"

class ConcreteVisitorB(AbstractVisitor):
         def visit(self, element):
                 element.label = "ConcreteVisitorB operated on this model"


model = SomeModel()

operatorA = ConcreteVisitorA()

model.accept(operatorA)

operatorB = ConcreteVisitorB()

model.accept(operatorA)

not_a_valid_type = "foo"

model.accept(not_a_valid_type)
</python>

The Pythonic way to deal with it is exactly how you deal with it above. When the script attempts to call model.accept(not_a_valid_type) an exception is raised, and the exception's traceback will tell you exactly what the problem was (namely that not_a_valid_type does not have a method called "visit"). In what way would runtime type-checking be any better than this? There's an obvious way in which it would be worse, namely that it would prevent the user from passing a custom object to SomeModel.accept() that has a visit() method but is not one of the types for which you thought to check.

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to