Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it okay to write own magic methods?

Tags:

python

In my web application I often need to serialize objects as JSON. Not all objects are JSON-serializable by default so I am using my own encode_complex method which is passed to the simplejson.dumps as follows: simplejson.dumps(context, default=self.encode_complex)

Is it okay to define my own magic method called __json__(self) and then use code similar to the following in encode_complex method?

def encode_complex(self, obj):
    # additional code

    # encode using __json__ method
    try:
        return obj.__json__()
    except AttributeError:
        pass

    # additional code
like image 628
Viktor Stískala Avatar asked Feb 15 '12 22:02

Viktor Stískala


2 Answers

The __double_underscore__ names are reserved for future extensions of the Python language and should not be used for your own code (except for the ones already defined, of course). Why not simply call the method json()?

Here is the relevant section from the Python language reference:

__*__
System-defined names. These names are defined by the interpreter and its implementation (including the standard library). Current system names are discussed in the Special method names section and elsewhere. More will likely be defined in future versions of Python. Any use of __*__ names, in any context, that does not follow explicitly documented use, is subject to breakage without warning.

like image 65
Sven Marnach Avatar answered Nov 13 '22 20:11

Sven Marnach


You probably don't want to use double underscore due to name mangling http://docs.python.org/reference/expressions.html#atom-identifiers -- However in concept what you're doing is fine for your own code.

like image 33
bradley.ayers Avatar answered Nov 13 '22 19:11

bradley.ayers