* Fix undefined vars on python3 and a whole bunch of other cleanup.
References #27193
* No need to catch exception and reraise. This just obfuscates the traceback
* Build up a list and then join at the end instead of building up a string. list.append() is faster than string concatenation
* No need to extract k, v pairs from one dict to make a second dict and then extract k, v pairs from the second dict. Iterate over the k, v pairs extracted from the first dict directly instead of building the second dict.
* No need to check if the dict is empty before iterating on it. Iterating on an empty dict will automatically go to the end of the loop
* Use isinstance instead of type(obj) is class, handles inheritance and is better style
* use to_native instead of v.encode(). We can use the surrogate_or_strict error handler to deal with more potential tracebacks. Does the right conversion on both Py2 and Py3.
* Convert bool to string before combining it with the string we're building.
* Don't reference unicode directly as unicode does not exist in Python3
* The string resulting from this function will not have a trailing comma
* Simplify the conversion to string int and bool values are now used in string formatting which will use str to transform them without an explicit invocation.