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.