Replies: 2 comments
-
|
On further reflection, this doesn't play nice with type linting. We could do something with May revisit this at some point from perspective of using |
Beta Was this translation helpful? Give feedback.
-
|
New idea struck; relevant portions of this discussion have been copied to discussion on reworking the parsing logic to better handle our |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Have so far had a hell of a time coming up with a good way to do "FromDict" approach to parsing and instantiating Schemas. Finally have what seems to be a solution that accomplishes the following two important things:
Old approach
Currently, each
Schemaclass is supposed to just implement aFromDictthat parses everything needed from a dict, and return an instance of the class.However, suppose we have a hierarchy where
SchemaBinherits fromSchemaB:Then
SchemaBwould need to redundantly parse out everything needed bySchemaAto call the super constructor, e.g.Redundancy isn't good, so we try to separate this out by adding a second layer, where there is a
_fromDictthat accepts pre-parsed params to pass directly to constructor, after parsing out subclass elements:However, this would require an additional level of "from dict" sub-function for each level of the hierarchy, and that's not clean at all.
An even older approach was to just have the
__init__function act as a de factoFromDict, where all required elements are parsed from a dictionary.However, this makes for really, really awkward functions that need to call the constructor but don't have a dictionary ready to go.
Writing such functions requires checking and double-checking exactly what is parsed by the init, to understand what keys to use in a custom-built dictionary.
That's not any fun, and it is much, much nicer to just use actual parameters, where linting and autocomplete help ensure the right data is passed in.
New Approach
The best solution I've come up with is as follows:
The
__init__functions should always assume class-specific params are optional and default to None, and fall back on a search ofother_elementsfor a missing value.The assumption is that all elements passed via
other_elementsand intended for the class have been parsed into the correct data type - no redundant parsing.Then the thing currently called
FromDictwill get renamed toParseDict, and return aDictof parsed elements. ThenFromDictcan callcls.ParseDict(...), merge withsuper().ParseDict(...), and put that all into the call to the init function.Sample:
This isn't perfect, as we don't really want the
__init__parameters to be optional with null defaults, but this gives a clean way to have parsing separated by class, but also allow us to have clearly-defined parameters for constructing objects.Beta Was this translation helpful? Give feedback.
All reactions