Note
Click here to download the full example code
Pickling#
Quickly cache and reload neurons with Python's pickle module.
All NAVis neurons - including whole NeuronLists - can be "pickled" . Pickling serialises the live Python object to a byte stream: it's extremely fast and ideal for short-term caching, with a couple of important caveats.
Caveats
Pickling is fast but is not a durable archival format:
- Pickle files can only be re-opened in Python.
- The pickled object is tied to your current environment. If you update Python, NAVis or even just
numpyorpandas, you may no longer be able to open an old file.
Never unpickle untrusted files
A pickle file can contain arbitrary Python code that runs the moment it is loaded. Only ever unpickle files you created yourself or that come from a source you fully trust.
With that out of the way, pickling is straightforward:
import navis
import pickle
# Load some example neurons
nl = navis.example_neurons(3, kind='mesh')
# Pickle the NeuronList to a file
with open('neurons.pkl', 'wb') as f:
pickle.dump(nl, f)
import pickle
# Read the neurons back from the pickle file
with open('neurons.pkl', 'rb') as f:
nl = pickle.load(f)
See also the I/O API reference.
Total running time of the script: ( 0 minutes 0.000 seconds)
Download Python source code: tutorial_io_04_pickle.py