Reputation: 1467
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
Upvotes: 13
Views: 6634
Reputation: 40414
As explained in other answers the double underscores shouldn't be used.
If you want to use a method with a name that implies that is to be used only by the internal implementation, then I suggest to use a single leading underscore.
As explained in PEP 8:
- _single_leading_underscore: weak "internal use" indicator. E.g. "from M import *" does not import objects whose name starts with an underscore.
Upvotes: 1
Reputation: 602325
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.
Upvotes: 21
Reputation: 38392
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.
Upvotes: 0