pipehappy <pipehappy <at> gmail.com> writes: > > Hello everyone: > > Is there a way to check the type when do assignment? > > if I write: > ab = bc > and want to make sure the return value of isinstance(bc, klass) is True > or I will raise > a exception. > > Any suggestion? >
1. Check your condition before the assignment: (IMO one-liners are over-rated) if not isinstance(bc, klass): raise TypeError # or do whatever else is appropriate ab = bc 2. If you really insist on doing this in a single statement (in the assignment itself), write a function for it: def assert_type(obj, klass): if not isinstance(bc, klass): raise TypeError return obj ab = assert_type(bc, klass) Or to be more generic: def assert_return(obj, func): assert func(obj) return obj ab = assert_return(bc, lambda obj:isinstance(obj, klass)) - Tal -- http://mail.python.org/mailman/listinfo/python-list