Skip to main content

Pickling

pyndb saves data using pickle by default. pickle is installed with python, and thus should not require installation.

Why pickle it?

Saving the data to file with pickle allows objects to be saved to file without force injecting a module into pyndb.

Here's an example:

plaintext solution:

# Saving the class to file
import pyndb
import datetime
db = pyndb.PYNDatabase('example.pyndb', filetype='plaintext')
db.set('test', datetime.datetime.now())
db.save()

import pyndb
import datetime
pyndb.datetime = datetime
# This injection is necessary for plaintext, as the __repr__ value of the datetime object is what's saved to file.
# It also must be performed before you load the database.
db = pyndb.PYNDatabase('example.pyndb', filetype='plaintext')
print(db.test.val)  # Will print the datetime object

pickled solution:

# Saving the class to file
import pyndb
import datetime
db = pyndb.PYNDatabase('example.pyndb')
db.set('test', datetime.datetime.now())
db.save()

import pyndb
db = pyndb.PYNDatabase('example.pyndb')
print(db.test.val)  # Will print the datetime object

How will this affect code from v2.x?

For now, backwards compatibility has been added, so when you attempt to open a plaintext file using the default setting (pickled) it will switch to plaintext for you. This will, however, throw a warning when the database loads, as this compatibility may be removed in the future. The option to set the file type to plaintext will remain, though.

Converting plaintext to pickle

To convert a plaintext file to pickled data, simply set the filetype flag to 'pickled' after initializing the PYNDatabase, and then call the save method.

Using plaintext instead

The master class has a filetype flag, which can be changed like so:

# Change on initialization
PYNDatabase(file, autosave=False, filetype='pickled')

# Change after initialization
PYNDatabase.filetype = 'plaintext'