I've noticed that while this does not work:
class MyClass:
def __init__(self, i):
self.5i = i
myobj = MyClass(5)
print(myobj.5i)
This does work:
class MyClass:
def __init__(self, i):
setattr(self, '5i', i)
myobj = MyClass(5)
print(getattr(myobj, '5i'))
Even more, this also works:
class MyClass:
def __init__(self, i):
self.__dict__['i.j'] = i
myobj = MyClass(5)
print(myobj.__dict__['i.j'])
Are snippets 2 and 3 guaranteed to work? Or do we rather have nasal demons here whose evil plan to bring innocent souls to hell is to make shenanigans of this kind seem to work, while in fact, they don't?
The reason I'm asking is that I'm converting JSON objects (received from an API) to classes. And since the server likes returning additional, undocumentend fields that sometimes do seem important, and I don't like loosing data... This is what most JSON-to-object conversions currently boil down to:
class FooResponse:
def __init__(self, json_string):
self.__dict__.update(json.loads(json_string))
But, but... What if the server returns a JSON with some very weird fields, like, for example:
{
"foo.bar": "Fizz-Buzz",
"1337": "speek"
}
Or whatever of this sort? Do I have to try my darndest to sanitize this or is simple self.__dict__.update(json.loads(json_string))
appropriate?
The server documents accepting JSON calls with field names that contain dots or are string representations of numbers, so I find it possible thatit might return such a JSON as well.