Deprecating fields in MongoEngine Documents

2015-07-26·· 1 min read
blog

I’ve had to rename some fields today with MongoEngine. Using the following approach, I was able to raise DeprecationWarnings when old version were used.

Create the following function. It returns a property that will access the new variable name.

def deprecated_field(new_name):
    """Wrapper for deprecated fields"""
    def getter(self):
        warnings.warn('This field is deprecated, use {}'.format(new_name),
                      DeprecationWarning,
                      stacklevel=2)
        return getattr(self, new_name)

    def setter(self, value):
        warnings.warn('This field is deprecated, use {}'.format(new_name),
                      DeprecationWarning,
                      stacklevel=2)
        return setattr(self, new_name, value)

    return property(getter, setter)

Now use this function whenever you need to deprecate something

class A:
    new_x = 'something'
    old_x = deprecated_field('new_x')

Trying to access A.old_x will now get the warning.

This will probably also work for regular Django Models, but I haven’t tested that.

Thom Wiggers
Authors
Senior Cryptography Researcher
Thom Wiggers is a cryptography researcher at PQShield. His PhD thesis was on the interactions of post-quantum cryptography with protocols, under the supervision of Peter Schwabe, at the Institute of Computing and Information Sciences, Radboud University in The Netherlands.