While writing some debugging python, I seem to have created a bit of ugly code that I would like to clean up.
Here is the function in its entirety:
def debug(message, variable=None):
if variable and DEBUG:
print("\n" + str(type(variable)))
try:
if isinstance(variable, (list, dict, 'OrderedDict')):
variable = json.dumps(
variable,
indent=4,
sort_keys=True
)
except TypeError:
if isinstance(variable, (list, dict)):
variable = json.dumps(
variable,
indent=4,
sort_keys=True
)
if DEBUG:
if variable:
print(message + str(variable) + "\n")
else:
print("\n" + message)
I specifically despise my try-except statement, because not only am I repeating code, but if I run into another dictionary class (like CaseInsensitiveDict from requests' headers) that I would like to print nicely during debugging output I would have to nest try-except statements.
Is there a way that I could check if type(variable)
is like *dict*
or *list*
then add it when creating the tuple for use in isinstance?