Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow setting the resulting dict class. #6

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

dourvaris
Copy link

Main use case would be something like:

from collections import OrderedDict

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

@danielholmstrom
Copy link
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
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