0

Is there an easy and more or less standard way to dump all the variables into a file, something like stacktrace but with the variables names and values? The ones that are in locals(), globals() and maybe dir(). I can't find an easy way, here's my code for "locals()" which doesn't work because the keys can be of different types:

vars1 = list(filter(lambda x: len(x) > 2 and locals()[x][:2] != "__", locals()))

And without filtering, when trying to dump the variables I get an error:

f.write(json.dumps(locals()))
# =>
TypeError: <filter object at 0x7f9bfd02b710> is not JSON serializable

I think there must be something better that doing it manually.

Steven
  • 177
  • 1
  • 1
  • 8
  • 1
    You must write custom serializator for all classes See: http://stackoverflow.com/questions/3768895/python-how-to-make-a-class-json-serializable – Maxim Panfilov Feb 15 '16 at 15:24
  • @MaximPanfilov, ты че, гонишь что-ли? а переменные? – Steven Feb 15 '16 at 15:29
  • json сериализует только базовые типы данных, так что придется для каждого небазового типа написать свой сериализатор. Можно еще использовать pickle и сериализовать такие данные в текст + base64, например, но такие данные можно будет десериализовать только в python. – Maxim Panfilov Feb 15 '16 at 15:48
  • 1
    [be nice](http://stackoverflow.com/help/be-nice). Use English on stackoverflow.com. Visit http://ru.stackoverflow.com if you need Russian. – jfs Feb 15 '16 at 17:07
  • it is not clear how `locals()` and "variables in a file" are connected. To get a list of all objects, you could use [`gc.get_objects()`](https://docs.python.org/3/library/gc.html#gc.get_objects). You probably want to ask instead: *"how to serialize as JSON an arbitrary Python object?"* – jfs Feb 15 '16 at 17:24

1 Answers1

1

To start, in your non-working example, you don't exactly filter the keys (which should normally only be strings even if it's not technically required); locals()[x] is the values.

But even if you did filter the keys in some way, you don't generally know that all of the remaining values are JSON serialisable. Therefore, you either need to filter the values to keep only types that can be mapped to JSON, or you need a default serialiser implementation that applies some sensible serialisation to any value. The simplest thing would be to just use the built-in string representation as a fall-back:

json.dumps(locals(), default=repr)

By the way, there's also a more direct and efficient way of dumping JSON to a file (note the difference between dump and dumps):

json.dump(locals(), f, default=repr)
Thomas Lotze
  • 5,153
  • 1
  • 16
  • 16