On 22 September 2017 at 10:05, Thomas Jollans <[email protected]> wrote: > On 2017-09-22 10:55, Ganesh Pal wrote: >> I have two possible values for Z_block in the block code i.e >> disk_object.data.data.di_data[0] or block.data.data.di_data.data[0][0] >> >> >> def get_block(): >> ''' Get Z block '' >> >> if block.data.data.di_data.data[0][0] is not None: >> Z_block = block.data.data.di_data.data[0][0] >> >> else: >> Z_block = disk_object.data.data.di_data[0] >> >> if not Z_block: >> return False >> >> return Z_block >> >> >> >> >> I have a problem with if and else satement i.e if IF codition fails the >> code would exit with "AttributeError: 'list' object has no attribute >> 'data' " error >> >> Any suggestion on how this can be handled better , Will ignoring the >> exceptions in try -except with pass be good or are there easier ways ) , >> >> >> try: >> Z_block = block.data.data.di_data.data[0][0]except AttributeError as e: >> >> pass > > > > try: > return self.some.attribute.or.another > except AttributeError: > return DEFAULT_VALUE > > is a perfectly good pattern to use.
getattr(obj, 'attr_name', DEFAULT_VALUE) may also be useful, although if more than one of the attribute lookups in the chain you show could fail, then catching the exception is probably simpler. Paul -- https://mail.python.org/mailman/listinfo/python-list
