MongoEngine / MongoEngine/mongoengine

Field order not preserved during redefinition.

Open
#1,321 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
4.3k
Forks
1.2k
Avg merge
4h 41m
Merged PRs (30d)
11

Description

There's a use case where subclassing is used for specialization and overriding of default values.

Take this example:

from mongoengine import Document, StringField

class Asset(Document):
    meta = dict(allow_inheritance=True)
    handler = StringField(default="web.component.asset:AssetController")
    path = StringField()

class Page(Asset):
    handler = StringField(default="web.component.page:PageController")

However, there is a bit of an issue that crops up when you have defined multiple fields, then override one this way.

print(Page._fields_ordered)
# ('id', 'path', 'handler', '_cls')

My own declarative schema system uses this chunk of metaclass to avoid this issue: https://github.com/marrow/schema/blob/develop/marrow/schema/meta.py#L60-L95 (apologies for the metaclass bit being exceptionally difficult to grok Python code… nature of the beast.)

Very specifically, this explicitly preserves declaration order for redefined fields:

from marrow.schema import Container, Attribute

class Foo(Container):
    handler = Attribute()
    path = Attribute()

class Bar(Foo):
    handler = Attribute()

print(Bar.__attributes__)
# handler, path - order preserved despite the redefinition getting a later sequence ID

This metaclass example may provide an approach to resolve this issue.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No source file or test is named in the issue. Start by tracing how inherited fields are collected into Page._fields_ordered, using the supplied Asset/Page example; done means the redefined handler retains its original position while the other fields remain ordered.

Written by the indexing model from the issue text.

Assessment

Tech stack
mongodb, python
Domain
backend, databases
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.