0

Is there a way where I'm able to generate the code in a file for a python data structure.

For example, if I had a dictionary, it would create a file with: name_of_variable = { key: value, key:value}

and so on. The use for this is testing where I don't want to manually code up a lot of data structures for my tests and I'd rather create some template structures where I can edit manually.

Thanks in advance.

3 Answers 3

3

For simple data structures such dict, list, set and other built-in things you can use repr():

>>> d = {'a': 2, 'b': 3, 'c': 4}
>>> repr(d)
"{'a': 2, 'c': 4, 'b': 3}"
>>> l = range(10)
>>> repr(l)
'[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]'
>>> s = set(range(10))
>>> repr(s)
'set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])'

Documentation says: ''For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval()''.

Sign up to request clarification or add additional context in comments.

Comments

1

Another Human-Friendly serialization format is YAML which can be accessed through the PyYAML module....

...or, for the quick'n'dirty import the module containing POP ("Plain Old Python") ;-)

Happy coding.

Comments

1

Yes, you can use JSON serialization. Since 2.6, Python has the json module in the standard library, and using it is really simple:

>>> import json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'

You can place this string in a file. Later you can read it back into a Python data structure with json.loads.


However, I'd also like to separately address this quote from your question:

I don't want to manually code up a lot of data structures for my tests and I'd rather create some template structures where I can edit manually.

If this is for testing purposes, I would seriously consider staying in the domain of Python code & data structures, and generate test data on the fly with Python code. The specifics of this are very much dependent on the exact nature of your data, but writing such data structures manually is a not a welcome task. You'll become bored too quickly to get good coverage of your code.

3 Comments

@pst: when all you need is serialization of Python data structures, JSON is IMHO a far better choice than XML
I'm not serious about XML ;-)
@pst: yeah. thankfully, XML is not very popular among Python hackers

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.