1

Context

Python integration in Vim 8.0 provides a handful of useful python objects in vim module. In particular, there are per-buffer objects accessible via vim.buffers list and vim.current.buffer. One can set or read per-buffer variables and options by accessing b.vars and b.options dict-like objects, where b is that buffer object.

Question

However, Vim variables are necessarily strings and one cannot store arbitrary python objects in there. How do I store an arbitrary per-buffer python object?

Failed attempts

I tried adding a custom attribute on the buffer object via setattr(b, ...) or via assigning to b.__dict__[...] but that does not work (these objects have no __dict__ or __setattr__()), same for subobjects.

It is also possible to have a global dictionary indexed by buffer number (b.number) and hook into the BufDelete autocmd for cleanup. This is what I use right now, but that feels kludgy and I seek a better solution, if there is one.

1 Answer 1

2

I often use those global, but plugin-internal, dictionaries indexed by buffer number, even in pure vim scripts. Sometimes, there is no better solution.

The advantage, also, is that I'm sure the variable is completly encapsulated, and there is no risk of seing another plugin using a variable with the exact same name, or messing with my invariants.

Otherwise, I wonder whether there isn't a way to turn a Python dictionary into a vim dictionary (as long as the Python dictionary only contains numbers, strings, dictionaries and arrays). I won't be surprised to see that someone has already implemented such a feature. BTW, a simple way would be to use json as a translation layer as Vim knows how to (de)serialize json data.

2
  • I'm trying to store arbitrary Python objects (not only dictionaries), so JSON serialization doesn't apply. I could try pickle, but I guess that would be really slow. So I guess I'll stick with the global dictionary approach.
    – intelfx
    Commented May 8, 2017 at 0:48
  • 2
    If only Vim autocommands could be a bit more sane...
    – intelfx
    Commented May 8, 2017 at 0:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.