Dynamically call methods in Python

It may be basic.

Why now? When I was communicating with WebSocket using tornado

Send callback method name with Javascript → Execute the method specified by tornado and send the callback function name to Javascript → Execute the callback function specified in Javascript

I wanted to call a method from a string.

First, connect to Javascript and WebSocket and send the calling method name and other parameters on the tornado side. The parameters are sent in JSON.

python


var ws = new WebSocket('ws://server/ws');
var p = {};
//callback method name
p['callback'] = 'wake_up';
//Other parameters
p['msg'] = 'Wake Up!!!!';
ws.send(JSON.stringify(p));
ws.onmessage = function(e) {
    var data = JSON.parse(e.data);
    console.log(data['message']);
};

The tornado side, getattr of on_message is the main part of this title.

app.py


from tornado import ioloop,web,websocket
import json
#callback class
from callback import Callback

class WSHandler(websocket.WebSocketHandler):
    #When the message comes
    def on_message(self, message):
        data = json.loads(message)
        #Instantiation of Callback class
        cb = Callback(data)
        #Method call
        result = getattr(cb, data['callback'])()
        
        #Value to return to Javascript
        return_value = {}
        return_value['message'] = result

        #Send message with WebSocket
        self.write_message(json.dumps(return_value))

handlers = [
    (r'/ws', WSHandler),
]

settings = dict(
    debug = False,
)

app = web.Application(handlers, **settings)
app.listen(sys.argv[1])
ioloop.IOLoop.instance().start()

The method to be called.

callback.py


class Callback(data):
    def __init__(self, data):
        self.data = data

    def wake_up(self):
        return self.data['msg']

You should now see'Wake Up !!!!'on your browser console.

The usage of getattr is as follows. Details are left to the official documentation.

python


cb = Callback(data)
result = cb.wake_up()

#The above is the same as the code below
result2 = getattr(cb, 'wake_up')()

#By the way, if you do as follows, the return value will not be returned and the object will be assigned.
result3 = getattr(cb, 'wake_up')

Did you do it like result3 above? ?? ?? But when you think about it, it's right. .. ..

2013-03-15 postscript Fixed a subtle mistake. Excuse me.

Recommended Posts

Dynamically call methods in Python
Dynamically define functions (methods) in Python
String object methods in Python
Dynamically import scripts in Python
Dynamically load json type in python
Quadtree in Python --2
Python in optimization
CURL in python
[Python3] Dynamically define global variables in functions
Metaprogramming in Python
Python 3.3 in Anaconda
SendKeys in Python
How to dynamically define variables in Python
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Constant in python
Private methods and fields in python [encryption]
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
How to dynamically zero pad in Python
Call sudo in Python and autofill password
Summary of built-in methods in Python list
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Call APIGateWay with APIKey in python requests
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
flatten in python
To dynamically replace the next method in python
Testing methods that return random values in Python
Call a Python script from Embedded Python in C ++ / C ++
[Python] Dealing with multiple call errors in ray.init
Sorted list in Python
Daily AtCoder # 36 in Python
Clustering text in Python
Daily AtCoder # 2 in Python
Implement Enigma in python
Daily AtCoder # 32 in Python