Is there a better way of storing a JSON entry

Question from Anonymous

class Event:
    def __init__(self, name, time, location):
        self.name = name
        self.time = time
        self.location = location

Is this a good thing to do or should I not

(Deleted User) I'd suggest a namedtuple instead. it's much faster and efficient.

Or dataclasses if you're using py 3.7.

How do I use a namedtuple?

Actually quick disclaimer.

The way python's JSON module works, it's impossible for you to dump namedtuples as anything other than a list.

Here you should just use a dictionary (IMO).

event = {"name": name,
         "time": time,
         "location": location}

But if I'm being honest that's just my clojure brain talking.

pro: If you deserialize from json you get this anyways and you can do round-trip serde and have the same representation.

con: The "shape" of the dict doesn't have a name and you can't use the . syntax to access stuff by default.

If you want to use the dot-notation for access with a dict just wrap it in this lib.

https://github.com/Infinidat/munch

In general, you don't gain much by "dressing up" your data though named tuples are immutable, which is nice.


<- Index