pythonobjectdynamic-data

Generating py objects via python


I was wondering if there was a rendering library that would take a dictionary object and render a file into py-object syntax. Similar to the django_extensions command dump_script. I've looked around for an hour but have got no success as of yet. I know it wouldn't take me long to create, but I want to see if there is a supported module for this.


Solution

  • You want to generate code from objects? This is possible for some built-in types so if you restrict yourself to them it works, and it's done with the repr() function.

    >>> dictionary = {'foo': 3, u'bar': [6.7]}
    >>> str = repr(dictionary)
    >>> str
    "{'foo': 3, u'bar': [6.7000000000000002]}"
    >>> exec("adict = " + str)
    >>> adict
    {'foo': 3, u'bar': [6.7000000000000002]}
    

    In general it's not particularly useful, so you might want to explain your use case.