I have my main.py
import application
def foo(args):
print("Invoked!")
def main():
app = application.Application()
# here i want to connect app.receivedMessage to foo
and my application.py
class Application:
def __init__(self):
pass
def receivedMessage(self, args):
# somehow call foo(args)
Basically how can I call foo and pass the args when receivedMessage is called. I have other pieces to the Application class that listen to a usb message and invoke 'receivedMessage'
Thanks
You could pass the foo function to your Application object:
class Application:
def __init__(self, foo):
self.foo = foo
def receivedMessage(self, args):
self.foo(args)
Passing the function as an argument works fine too.
#!python3
class Application:
def __init__(self):
pass
def receivedMessage(self,args,**kwargs):
if kwargs and kwargs['foo']:
foo=kwargs['foo']
foo(args)
def foo(args):
print('Invoked')
if __name__=='__main__':
app = Application()
app.receivedMessage("haha", foo=foo) # works
app.receivedMessage("haha") # doesn't raise error
Related
I would like to find all instances in the code where np.random.seed is called (without using grep). In order to set a breakpoint in ipdb, I tried to find the source file with
import inspect; inspect.getsourcefile(np.random.seed)
but it throws a TypeError because it is a built-in method (because it is coded in C).
Is it possible to watch any calls to np.random.seed by modifying something in the main source file?
Additionally, it would be suitable to patch this method, e.g. additionally logging it (or calling a debugger):
def new_random_seed(seed):
"""
This method should be called instead whenever np.random.seed
is called in any module that is invoked during the execution of
the main script
"""
print("Called with seed {}".format(seed))
#or: import ipdb; ipdb.set_trace()
return np.random.seed()
Maybe using a mock framework is the way to go?
The second question concerns the scenario in which a class B inherits from a class A in a library and I want to use the functionality of class B, but overwrite a function it uses from class A without modifying classes A and B. Probably, I should use mocking, but I am not sure about the overhead, so I wrote the following:
#in library
class A():
def __init__(self, name):
self.name = name
def work(self):
print("{} working".format(self.name))
class B():
def __init__(self):
self.A = A("Machine")
def run_task(self):
self.A.work()
# in main script
# Cannot change classes A and B, so make a subclass C
import types
class C(B):
def __init__(self, modified_work):
super().__init__()
self.A.work = types.MethodType(modified_work, self.A) #MethodType for self
b = B()
b.run_task()
modified_work = lambda self: print("{} working faster".format(self.name))
c = C(modified_work)
c.run_task()
The output is:
Machine working
Machine working faster
Is this good style?
This might be a simpler solution to your second question:
# lib.py
class A():
def work(self):
print('working')
class B():
def __init__(self):
self.a = A()
def run(self):
self.a.work()
Then in your code:
import lib
class A(lib.A):
def work(self):
print('hardly working')
lib.A = A
b = lib.B()
b.run()
Or:
import lib
class AA(lib.A):
def work(self):
print('hardly working')
class BB(lib.B):
def __init__(self):
self.a = AA()
b = lib.B()
b.run()
b = BB()
b.run()
I am trying to create a class called ListenerVilma that has two methods: "Clock_" and "Diagnostics_". Nevertheless both methods will call inner functions. The following code shows my attempt to achieve the mentioned behavior, but when I call ListenerVilma.Clock_() the get the following error:
TypeError: unbound method Clock_() must be called with ListenerVilma instance as first argument (got nothing instead)
How should a create my class ListenerVilma???
Thanks.
#!/usr/bin/env python
import rospy
from rosgraph_msgs.msg import Clock
from diagnostic_msgs.msg import DiagnosticArray
class ListenerVilma:
"""Class that listens all topics of the file vilmafeagri"""
def Clock_(self):
"""Method that listens the topic /clock if the file vilmafeagri"""
def __init__(self):
self.listener()
def callback(self, clock):
print clock
def listener(self):
rospy.Subscriber('clock', Clock, self.callback)
def Diagnostics_(self):
"""Method that listen the topic /diagnostics from rosbag file vilmafeagri"""
def __init__(self):
self.listener()
def callback(self, diagnostics):
print diagnostics
def listener(self):
rospy.Subscriber('diagnostics', DiagnosticArray, self.callback)
if __name__ == '__main__':
rospy.init_node('listener', anonymous=True)
ListenerVilma.Clock_()
rospy.spin()
the error is in line 41 in ListenerVilma.Clock_() here your directly using the method of your class so no implicit argument is pass and a instance of ListenerVilma is expected. The solution is ListenerVilma().Clock_() this first create a instance of your class and from say instance call its Clock_ method.
Outside that, your class construction is very weird, the __init__ is used to initialize a class and a basic class construction is like this
class Foo:
"""example class"""
def __init__(self,*argv,**karg):
"""initialize this class"""
#do something with argv and/or karg according to the needs
#for example this
print "init argv", argv
print "init karg", karg
self.ultimate=42
def do_stuff(self):
"""this method do something"""
print "I am doing some stuff"
print "after 7.5 million years of calculations The Answer to the Ultimate Question of Life, the Universe, and Everything is: ", self.ultimate
def do_some_other_stuff(self,*argv,**karv):
"""this method do something else"""
print "method argv", argv
print "method karg", karg
# basic usage
test = Foo(1,2,3,key_test=23)
test.do_stuff()
test.do_some_other_stuff(7,8,9,something=32)
test.ultimate = 420
test.do_stuff()
I am not quite sure what you intentions are, but you build Clock_ and Diagnostics_ as a class, but they are not, and as right now they do nothing, if you want they to be class on their own do
class Clock_:
def __init__(self):
self.listener()
def callback(self, clock):
print clock
def listener(self):
rospy.Subscriber('clock', Clock, self.callback)
and the same with Diagnostics_, and I don't see a reason to the listener method so I would put what it does in the __init__, but maybe the rospy need it? I don't know, but for the looks of it then it should be used as
rospy.init_node('listener', anonymous=True)
Clock_()
Diagnostics_()
rospy.spin()
The Clock_ method doesn't belong to the class; it's an 'instance' method.
There are two options
In the main function: create an instance of ListenerVilma: listener = ListenerVilma(), or
In the ListenerVilma class: annotate the methods with #classmethod and make the class inherit from object: class ListenerVilma(object):. But remember, the first argument in your methods will be a reference to the class and not a reference to an instance.
The following code performs better the behavior that I wanted. :)
class ListenerVilma:
def CLOCK(self):
def clock_sub():
rospy.Subscriber('clock', Clock, clock_callback)
def clock_callback(clock):
print clock
clock_sub()
def DIAGNOSTICS(self):
def diagnostics_sub():
rospy.Subscriber('diagnostics', DiagnosticArray, diagnostics_callback)
def diagnostics_callback(diagnostics):
print diagnostics
diagnostics_sub()
if __name__ == '__main__':
rospy.init_node('listener', anonymous=True)
myVilma = ListenerVilma()
myVilma.CLOCK()
myVilma.DIAGNOSTICS()
rospy.spin()
In a ipython script notebook I want to have something like:
from mod import run
def initialize():
print("In!")
run()
The script makes the assumption the user needs to define a function initialize, and the run() should test if it is defined and invoke it.
How should I define run() to get a reference to a "initialized" function defined in the interactive namespace ?
Here is one possible approach -
Inside the module:
class MyHandler(object):
def __init__(self, *args):
""" Init stuff """
def run(self, *args):
self.initializer(*args)
"""do running stuff"""
pass
def initializer(self):
raise Exception("Initializer must be defined")
def shutdown(self):
"""default cleanup stuff"""
pass
Then the Ipython workflow could be something like:
from mod import MyHandler
new_handler = MyHandler()
def add_method(obj, meth):
obj.__dict__[meth.__name__] = meth.__get__(obj, obj.__class__)
def intializer(self):
print("In!")
add_method(new_handler, initializer)
new_handler.run()
I wrap Bottle in a class and would like to bottle.route() error handlers. Is this possible? I currently use decorators on unbound functions as described in the docs (the comments reflect how I would like to change the code)
import bottle
class WebServer(object):
def __init__(self):
self.message = "hello world"
bottle.route("/", 'GET', self.root)
# bottle.route(error 404 to self.error404)
bottle.run(host='0.0.0.0', debug=True)
def root(self):
print("hello from root")
#bottle.error(404)
def error404(error):
# I would like to print self.message here after the routing above
print("error 404")
return
if __name__ == "__main__":
WebServer()
Note: I read the warning in another SO thread about not doing the routing in __init__ but I will be using only one instance of the class.
You should be able to define your error handler within Webserver.__init__:
import bottle
class WebServer(object):
def __init__(self):
self.message = "hello world"
bottle.route("/", 'GET', self.root)
# just define your error function here,
# while you still have a reference to "self"
#bottle.error(404)
def error404(error):
# do what you want with "self"
print(self.message)
return self.message
bottle.run(host='0.0.0.0', debug=True)
def root(self):
print("hello from root")
if __name__ == "__main__":
WebServer()
from __future__ import with_statement
from sikuli.Sikuli import *
import os
import unittest
import this
import xmlrpclib
import SimpleXMLRPCServer, SocketServer, threading
class SimpleThreadedXMLRPCServer(SocketServer.ThreadingMixIn, SimpleXMLRPCServer.SimpleXMLRPCServer):
pass
class ABC(object):
def A(self):
...........
def B(self):
...........
def C(self):
...........
class XYZ(unittest.TestCase,ABC):
def setUp(self):
print "Inside setup"
pass
def tearDown(self):
print "Inside tearDown"
pass
def test_1(self):
self.A()
self.B()
self.C()
def D(self):
print "Inside D"
return True
suite = unittest.TestLoader().loadTestsFromTestCase(XYZ)
class ServerThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.server = SimpleThreadedXMLRPCServer(("x.x.x.1", 8000))
#self.server.register_instance() #How to Register an instance of XYZ here.
def run(self):
self.server.serve_forever()
server = ServerThread()
server.start()
So my question is that how to Register an instance of XYZ here. In the commented line above so that it can be called from the XMLRPC client like:
client = xmlrpclib.ServerProxy("http://x.x.x.2:8000")
handraise = client.D() #Or any other possible way
I know it works with register_function(D) but I want the whole class XYZ to be exposed using register_instance().
Theoretically this should work:
self.server.register_instance(XYZ()) # but it throwed some runTest Error for me
Anyways, passing the method name explicitly as an arg in the Classname inside register_instance like:
self.server.register_instance(XYZ("D"))
worked as expected for me.
And from the xmlrpc client, call the D() like:
handraise = client.D()