0

I am writing a kind of 'universal' json decoder that would convert everything it can using a default json encoder plus sets, and everything else it will convert using str() - which is a bit stupid, but it will allow to just work silently and let users know what kind of data there was initially.

So with the small amendment the following code is taken from here:

import json
class SetEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, set):
            return list(obj)
        try:
            return json.JSONEncoder.default(self, obj)
        except TypeError:
            return str(obj)

Then if I try to convert a function using this encoder it will return something like:

'<function a at 0x10ddd8f28>'

Which is, again a bit stupid but totally fine for my purposes.

The question is: what if str() fails to convert anything provided as an input argument? What kind of error will be triggered? I looked through str source and didn't get when exactly (if at all?) it captures the possible conversion errors. Or it is assumed to convert any kind of input provided?

Philipp Chapkovski
  • 1,949
  • 3
  • 22
  • 43

1 Answers1

1

You can check out the documentation of str:

If neither encoding nor errors is given, str(object) returns object.__str__(), which is the “informal” or nicely printable string representation of object. For string objects, this is the string itself. If object does not have a __str__() method, then str() falls back to returning repr(object).

That said. Besides situations like not being able allocate any more memory (MemoryError) which would not be str conversion specific, the only way I can see this failing is if someone overloaded __str__ (or __repr__ if there is no __str__) and made it to, for instance:

class C:
    def __str__(self):
        msg = "'{}' instance is not meant to be represented as str."
        raise ValueError(msg.format(self.__class__))

Which would result in:

>>> c = C()
>>> str(c)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in __str__
ValueError: '<class '__main__.C'>' instance is not meant to be represented as str.

That said though: There isn't really a generic answer to your question, because it could raise anything anyone programmed it to do.

EDIT: All of above pertains to simple str calls with just an object passed as seen in your example. If you attempt decoding the incoming object by specifying encoding and/or errors. You could run into TypeError for anything other then bytes-like input or see decoding related failures: UnicodeDecodeError. This behavior of str is described in the following paragraph of its docs:

If at least one of encoding or errors is given, object should be a bytes-like object (e.g. bytes or bytearray). In this case, if object is a bytes (or bytearray) object, then str(bytes, encoding, errors) is equivalent to bytes.decode(encoding, errors). Otherwise, the bytes object underlying the buffer object is obtained before calling bytes.decode().

Ondrej K.
  • 8,841
  • 11
  • 24
  • 39