Skip to content Skip to sidebar Skip to footer

Json.dumps() Give Unexpected Result When Passing A Variable Of Subclass Of Str In Python 2.7

I wrote a subclass of str like this: class URL(str): def __init__(self, url): u = normalize_url(url) print u super(URL, self).__init__(string=u) normal

Solution 1:

str (like other immutable objects) does it's initialization in __new__

Construction of an object in python roughly looks like this:

inst = cls.__new__(cls, *args, **kwargs)
cls.__init__(inst, *args, **kwargs)

In your example, you call __init__, but it is too late, the object has already been set up in __new__

You can however fix this!:

classURL(str):
    __slots__ = ()

    def __new__(cls, val):
         val = val.replace(' ', '%20')
         returnsuper(URL, cls).__new__(cls, val)

Now it works!

>>>x = URL('foo bar')>>>x
'foo%20bar'
>>>json.dumps(x)
'"foo%20bar"'

Note that I've added __slots__ = () to restore the immutability that str had.

Post a Comment for "Json.dumps() Give Unexpected Result When Passing A Variable Of Subclass Of Str In Python 2.7"