Skip to content

Allow setting the resulting dict class.#6

Open
dourvaris wants to merge 1 commit intodanielholmstrom:masterfrom
dourvaris:master
Open

Allow setting the resulting dict class.#6
dourvaris wants to merge 1 commit intodanielholmstrom:masterfrom
dourvaris:master

Conversation

@dourvaris
Copy link
Copy Markdown

Main use case would be something like:

from collections import OrderedDict

some_object.asdict(only=['id', 'parent_id', 'name'], DictClass=OrderedDict)

@danielholmstrom
Copy link
Copy Markdown
Owner

@dourvaris

I cannot figure out why anyone would like to use a custom dict class. If you want to, as in your use case, use an OrderedDict then what would determine the order? And why would you care for the order?

@dourvaris
Copy link
Copy Markdown
Author

I cannot figure out why anyone would like to use a custom dict class.

Well firstly this is not limited to ordered dicts only, you could pass any type of class that would be used as the base for the output dict which makes, a good example would be something like https://github.com/dimagi/jsonobject.

Using a JsonObject class, the resulting dict like object for json could follow a strict schema of fields in the final json output (to catch bugs early) and it can also do automatic 2-way deserialization of datetime so that python side obj.created returns a datetime, and as_json() returns isoformat() or whatever.

If you must ask why not just call the class on the resulting dict from dictalchemy, sure, but then you would also have to follow all the relationships etc. in essence reimplement dictalchemy.utils.asdict.

If you want to, as in your use case, use an OrderedDict then what would determine the order? And why would you care for the order?

You could ask the same question about why OrderedDict exists in the first place, yet it exists. A simple issue would be when displaying/formatting the dict, you would like the order to be fixed and usually the more important fields higher up. eg.

{
  'id': 88,
  'username': 'someperson',
  'friends': [
    {
     'id': 12,
     'username': 'otherguy'
    },
    {
     'id': 62,
     'username': 'him'
    },
    ... 10 other entries ...
  ]
}

vs

{
  'friends': [
    {
     'id': 12,
     'username': 'otherguy'
    },
    {
     'id': 62,
     'username': 'him'
    },
    ... 10 other entries ...
  ],
  'id': 88,
  'username': 'someperson',
}

Order would be determined by only for overriding, otherwise by the sqlalchemy schema definition which is also ordered internally.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants