How to write an empty indentation block in Python?
Just write
pass
as in
try: # Do something illegal. ...except: # Pretend nothing happened. pass
EDIT: @swillden brings up a good point, viz., this is a terrible idea in general. You should, at the least, say
except TypeError, DivideByZeroError:
or whatever kinds of errors you want to handle. Otherwise you can mask bigger problems.
For those who are very unclear as to why you would want to do this. Here is an example where I initially thought that an empty block would be a good idea:
def set_debug_dir(self, debug_dir=None): if debug_dir is None: debug_dir = self.__debug_dir elif isinstance(debug_dir, (Path, str)): debug_dir = debug_dir # this is my null operation elif isinstance(debug_dir, list): debug_dir = functools.reduce(os.path.join, debug_dir) else: raise TypeError('Unexpected type for debug_dir: {}'.format(type(debug_dir).__name__))
But it would be more clear to reorganize the statement:
def set_debug_dir(self, debug_dir=None): if debug_dir is None: debug_dir = self.__debug_dir elif isinstance(debug_dir, list): debug_dir = functools.reduce(os.path.join, debug_dir) elif not isinstance(debug_dir, (Path, str)): raise TypeError('Unexpected type for debug_dir: {}'.format(type(debug_dir).__name__))
I've never done this in more permanent code, but I frequently do it as a placeholder
if some_expression: Trueelse: do_something(blah)
Just sticking a True in there will stop the error. Not sure if there's anything bad about this.