Is It Possible To Store Python Objects in PostgreSQL?

Question:
Is it possible to store a Python object (class) I made in Replit’s PostgreSQL?

Even if you can’t, you can still stringify it and then parse it out later.

2 Likes

(I don’t know a lot about and don’t use databases.)

Almost any python object, custom or builtin, can be represented as a more common format like a JSON string, or bits.

You are most likely looking for json — JSON encoder and decoder — Python 3.12.1 documentation, where you can easily take a custom object and store its __dict__ in JSON format in the database.
Sometimes, the repr() of an object also works if it is very simple. This is obviously less secure.

Another option is pickle — Python object serialization — Python 3.12.1 documentation.

1 Like

How could I pickle a simple object? Saying the object is as follows:

class thing:
  def __init__(self):
    self.test = "hello"

I prefer the json library imo

1 Like

Why pickle? JSON is easier IMO.

import json


class Thing():

    def __init__(self):
        self.test = "hello"

    def __dict__(self):
        return {"test": self.test}


# Store this
thing_json = json.dumps(Thing())

I don’t want to use JSON b/c I don’t want to have to add the attributes from the dict (from the JSON) back into the function. I’d rather pickle it.