Generate variable definition code from runtime data structure

103 views Asked by At

Say I have a dict at hand at runtime, is there an easy way to create code that defines the dict. For example it should output the string

"d = {'string_attr1' : 'value1', 'bool_attr1': True}"

Of course it would be possible to write a converter function by hand, which iterates over the key-value pairs and puts together the string. Would still require to handle special cases to decide if values have to be quoted or not, etc.

More generally: Is there a built in way or a library to generate variable declarations from runtime data structures?

Context: I would like to use a list of dicts as input for a code generator. The content of the dicts would be queried from an SQL database. I don't want to tightly couple code generation to the querying of the SQL database, so I think it would be convenient to go with generating a python source file defining a list of dictionaries, which can be used as an input to the code generator.

1

There are 1 answers

0
TessellatingHeckler On BEST ANSWER
>>> help(repr)
Help on built-in function repr in module __builtin__:

repr(...)
    repr(object) -> string

    Return the canonical string representation of the object.
    For most object types, eval(repr(object)) == object.