Skip to content

Instantly share code, notes, and snippets.

@gregorynicholas
Created February 7, 2013 02:09
Show Gist options
  • Select an option

  • Save gregorynicholas/4727815 to your computer and use it in GitHub Desktop.

Select an option

Save gregorynicholas/4727815 to your computer and use it in GitHub Desktop.
Pretty prints a mongoengine.Document.
def pprint_doc(doc, level=1):
'''Pretty prints a `mongoengine.Document`.'''
body = ['<', type(doc).__name__, ':']
# for field in sorted(doc._fields, key=lambda f: f.number):
for key, field in doc._fields.iteritems():
value = doc[key]
if value is not None:
body.append('\n%s%s: %s' % (' '.join([' ' for idx in range(level)]), key, repr(value)))
body.append('>')
return ''.join(body)
@ivan-kleshnin

Copy link
Copy Markdown

With a few tweaks to idea and implementation:

class PPrintMixin:
    def __str__(self):
        return '<{}: id={!r}>'.format(type(self).__name__, self.id)

    def __repr__(self):
        attrs = []
        for name in self._fields.keys():
            value = getattr(self, name)
            if isinstance(value, (Document, EmbeddedDocument)):
                attrs.append('\n    {} = {!s},'.format(name, value))
            else:
                attrs.append('\n    {} = {!r},'.format(name, value))
        return '<{}: {}\n>'.format(type(self).__name__, ''.join(attrs))

class MyModel(PprintMixin, Document):
    ...

print(MyModel.objects.get()) # short version
print(repr(MyModel.objects.get())) # full version

@jorge-lavin

Copy link
Copy Markdown

class PPrintMixin should inherit from object, mongoengine will inspect and will raise an AttributeError because of no __class__ attribute

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