Search code examples
pythonclassdata-structuresdata-modelinginner-classes

Python data structure/object to model static multidimensional table


I'm just getting back into coding after a few year hiatus and I'm trying to model multi-tiered static forms in a way that lets me grab and perform operations on a specific form level or an entire sub-tree.

Example Form hierarchy:

  • MyForm
    • Question 1
    • Part 1
      • Question 1.1
    • Part 2
      • Question 2.1
      • SubPart 1
        • Question 2.1.1
        • Question 2.1.2
    • Question 2

Each Question will have multiple attributes (question text, whether it's a required field, etc.) and Questions can be at any level of the hierarchy.

I'd like to be able to do something like this:

>>> MyForm.getQuestionObjects()
[Question1, Question1_1, Question2_1, Question2_1_1, Question2_1_2, Question2]

>>> MyForm.Part2.getQuestionObjects()
[Question2_1, Question2_1_1, Question2_1_2]

and/or stuff like:

>>> # Get questions (return class members)
>>> MyForm.SubPart1.getQuestions()
(('2.1.1 text', otherAttributes), ('2.1.2 text', otherAttributes))

>>> # Get questions -- but replace an attribute on 2.1.2
>>> MyForm.Part2.getQuestions(replace_attr('Question_2_1_2', 'text', 'New text'))
(('2.1.1 text', otherAttributes), ('New text', otherAttributes))

I keep trying to do this with nested/inner classes, which are a big headache and not well-supported in python. But even if I can figure out a solution using nested classes, I keep wondering whether there's a much better way of storing this form info somewhere to make it easier for non-coders to edit (probably a plain text template), and then loading the data at run-time since it's static and I'll need it in memory quite often. The form data won't be updated more than say once per month. Regardless how I store the data, I'd like to figure out a good data structure to represent, traverse, and operate on it.

  • Is there a way to make a tiered-attributes object like this?
  • Could I do something like multidimensional named tuples?
  • Any other ideas?

Thanks for any comments.


Solution

  • I'd store such hierarchical data in XML on the storage. You can use the xml.etree.ElementTree standard module to load such an XML file into a hierarchical data structure in Python, make changes to it, then save it back to a file. This way you don't have to bother with the actual data structure, since it is built by ElementTree automatically.

    See xml.etree.ElementTree in the Python Manual. More information can be found here:

    (There're other mature solutions in Python to load an XML file into various data structures. Just pick one which is the easiest to use for your task. Google is your friend. :-) )