Can I write my own magic methods?

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

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

 def encode_complex(self, obj): # additional code # encode using __json__ method try: return obj.__json__() except AttributeError: pass # additional code 
+4
source share
3 answers

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

Here is the relevant section from the Python link :

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

+9
source

You probably don't want to use a double underscore because of the name change http://docs.python.org/reference/expressions.html#atom-identifiers - However, in the concept, what you do is great for your own code.

+2
source

As explained in other answers, double underscores should not be used.

If you want to use a method with a name that implies that it will only be used by the internal implementation, I suggest using one leading underscore.

As explained in PEP 8 :

  • _single_leading_underscore: weak indicator of "internal use". For instance. "from M import *" does not import objects whose name begins with an underscore.
0
source

Source: https://habr.com/ru/post/1396735/


All Articles