in the below code, i am trying to develop using the concept of multithreading and synchronization.
i developed the below code. however, at the run time, i receive the below error:
cls: <class '__main__.ThreadsWithSync'>
Traceback (most recent call last):
File "m:\python lessons\ThreadsWithSync.py", line 68, in <module>
t1.spawnThread
AttributeError: 'NoneType' object has no attribute 'spawnThread'
PS M:\python lessons>
please let me know why the method 'spawnThread' is not recognized
import threading
import logging
import time
from random import seed
from random import randint
class ThreadsWithSync():
def __new__(cls):
"""
For object creation
"""
print("cls: %s"%(cls))
cls.onCreateObject()
def __init__(self):
"""
For object initialization
"""
#print("self: %s"%(self))
self.onInitializeObject()
#classmethod
def onCreateObject(cls):
"""
This will be invoked once the creation procedure of the object begins.
"""
instance = super(ThreadsWithSync, cls).__new__(cls)
#print("instace: %s"%(instance.__repr__)) #activate this line whenever an informative and descriprtive text about the instance is needed to be displayed
return instance
def onInitializeObject(self):
"""
This will be invoked once the initialization procedure of the object begins.
"""
threading.Thread.__init__(self) #to initialize the super class
print("self: %s"%(self))
seed(1)
def __repr__(self):
"""
similar to toString in Java
"""
return "\n__class__: " + repr(self.__class__) +"\n__new__:" + repr(self.__new__) + "\n__str__: " + repr(self.__str__) + "\n__sizeof__: " + repr(self.__sizeof__)
def isNumPrime(self, targetNum):
if targetNum == 0 or targetNum == 1:
return False
isPrim = True
for i in range(targetNum):
if targetNum % i == 0:
isPrim = False
break
return isPrim
def spawnThread(self):
if __name__ == "__main__":
main()
def main():
while True:
thread_1 = threading.Thread(group = None, target = self.isNumPrime, name='Thread_1', args = (), kwargs=dict(targetNum=randint(0,100)), daemon = None)
thread_2 = threading.Thread(group = None, target = self.isNumPrime, name='Thread_2', args = (), kwargs=dict(targetNum=randint(0,100)), daemon = None)
t1 = ThreadsWithSync()
t1.spawnThread
You forgot to return the created object from __new__
Related
#these classes live inside exchanges/impl/tse/mixins.py
class PacketContext:
capture_tstamp = None
def __init__(self, capture_tstamp=None):
self.capture_tstamp = capture_tstamp
class SubParserMixin():
def __init__(self):
self.context = PacketContext()
def on_packet(self, packet):
self.context.capture_tstamp = packet.capture_timestamp
self.parse_er_data(packet.payload)
#this mock test lives in another python file
from exchanges.impl.tse.mixins import PacketContext
#patch.object(PacketContext, 'capture_tstamp', 1655417400314635000)
def test_receive_timestamp(self):
"""
test receive_timestamp is passed down correctly from PacketContext to on_packet()
"""
assert self.context.capture_tstamp == 1655417400314635000
I am trying to mock the self.capture_tstamp attribute in the PacketContext() class.
But in the above, I am getting an error that says
AssertionError: assert None == 1655417400314635000
E + where None = <exchanges.impl.tse.mixins.PacketContext object at 0x7fb324ac04c0>.capture_tstamp
E + where <exchanges.impl.tse.mixins.PacketContext object at 0x7fb324ac04c0> = <tests.unit.exchanges.tse.test_quote_write.TestTSE testMethod=test_receive_timestamp>.context
It seems very strange that the program is not recognising PacketContext().
You can make use of the patch.object decorator as below
class PacketContext:
capture_tstamp = None
def __init__(self, capture_tstamp=None):
self.capture_tstamp = capture_tstamp
<import_PacketContext_here>
#patch.object(PacketContext, 'capture_tstamp', 1655417400314635000)
def test_receive_timestamp():
test_instance = PacketContext()
assert test_instance.capture_tstamp == 1655417400314635000
I have an task to do to figure out what the code below does. it looks like it was constructed in python2 but I want to use python3. I have installed argparse which it requires and set up necessary file path but every time I run the program in command Line I get these issues.
Traceback (most recent call last):
File "C:\Users\Name\pythonScripts\Noddy.py", line 6, in <module>
class Noddy:
File "C:\Users\Name\pythonScripts\Noddy.py", line 63, in Noddy
if __name__ == '__main__': main()
File "C:\Users\Name\pythonScripts\Noddy.py", line 57, in main
ent = Noddy.make(fools)
NameError: name 'Noddy' is not defined
The code is below.
#! python3
class Noddy:
def __init__(self, x):
self.ant = None
self.dec = None
self.holder = x
#classmethod
def make(self, l):
ent = Noddy(l.pop(0))
for x in l:
ent.scrobble(x)
return ent
def scrobble(self, x):
if self.holder > x:
if self.ant is None:
self.ant = Noddy(x)
else:
self.ant.scrobble(x)
else:
if self.dec is None:
self.dec = Noddy(x)
else:
self.dec.scrobble(x)
def bubble(self):
if self.ant:
for x in self.ant.bubble():
yield x
yield self.holder
if self.dec:
for x in self.dec.bubble():
yield x
def bobble(self):
yield self.holder
if self.ant:
for x in self.ant.bobble():
yield x
if self.dec:
for x in self.dec.bobble():
yield x
def main():
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("foo")
args = ap.parse_args()
foo = open(args.foo)
fools = [int(bar) for bar in foo]
ent = Noddy.make(fools)
print(list(ent.bubble()))
print
print(list(ent.bobble()))
if __name__ == '__main__': main()
Your def main() and if __name__=='__main__' have been written inside your class. The interpreter tries to execute them while it is defining the class, and can't, because the class Noddy doesn't exist until the class definition is finished.
Fix the indentation so that the main stuff lies outside your class.
class Noddy:
def __init__(self, x):
self.ant = None
self.dec = None
self.holder = x
# other methods INSIDE the class
# ...
# Notice the indentation — this function is OUTSIDE the class
def main():
# whatever main is supposed to do
# ...
if __name__=='__main__':
main()
I using the wx library to build a GUI. I have initialized a panel and intialized some push buttons and have binded a function that will execute when pushed. The function takes a list of arguments, one which is a callback function. What I am trying to do is redefine the callback function during runtime but I am failing to do so.
My attempt so far is:
self.UpdateCurrent = None
self.GetCurrent = None
self.UpdateCellVoltage = None
self.GetCellVoltage = None
self.UpdateCellTemperature = None
self.GetCellTemperature = None
self.battery_control_d = OrderedDict([('Current',[self.UpdateCurrent, self.GetCurrent, None, 1]),
('Cell Voltage',[self.UpdateCellVoltage, self.GetCellVoltage, 0, 24]),
('Cell Temperature',[self.UpdateCellTemperature, self.GetCellTemperature, 0, 24])])
.
.
.
submit_btn_l[-1].Bind(wx.EVT_BUTTON,
lambda evt,
io_name = io_name,
callback_fn = self.battery_control_d[io_name][0],
ctrl_textbox = ctrl_textbox,
dim_combobox = self.dim_combobox_l[-1]:
self._send_control_value(evt,
io_name,
callback_fn,
ctrl_textbox,
dim_combobox))
.
.
.
def init_battery_intf(self):
self.battery_intf = self.simulator_main_panel.battery_intf
self.UpdateCurrent = self.battery_intf.UpdateCurrent
self.GetCurrent = self.battery_intf.GetCurrent
self.UpdateCellVoltage = self.battery_intf.UpdateCellVoltage
self.GetCellVoltage = self.battery_intf.GetCellVoltage
self.UpdateCellTemperature = self.battery_intf.UpdateCellTemperature
self.GetCellTemperature = self.battery_intf.GetCellTemperature
.
.
.
def _send_control_value(self,
evt,
io_name,
callback_fn,
ctrl_textbox,
dim_combobox):
io_value = float(ctrl_textbox.Value)
if ("Temperature" in io_name):
io_value -= self.simulator_main_gui.temperature_unit_converter
callback_fn(io_value, int(dim_combobox.Value))
def update( self,
evt ):
for io_name, io_info in self.battery_control_d.iteritems():
io_value = float(io_info[1](io_info[2]))
self.reading_text_l[self.io_indexer.index(io_name)].SetLabel(" %.4f " % (io_value))
I predefine some update/get objects.
I bind the function to the buttons
During runtime I call init_battery_intf to initialize these objects
The line that errors out is when I try to call the callback function. It seems to be still be set to None.
Traceback (most recent call last):
File "C:\Users\Sam\Desktop\work\simulator\src\simulate.py", line 1185, in updat
self.control_notebook.update(evt)
File "C:\Users\Sam\Desktop\work\simulator\src\simulate.py", line 869, in update
self.battery_control_panel.update(evt)
File "C:\Users\Sam\Desktop\work\simulator\src\simulate.py", line 591, in update
io_value = float(io_info[1](io_info[2]))
TypeError: 'NoneType' object is not callable
I know I could redefine the bind and feed in the values directly, but I wanted to keep my code clean and simple, and I feel like Python has a way to distribute the redefined callback function to all instances of the object.
I'm using Python 2.7.
You have a few options:
A: Have self.UpdateCurrent and the other methods used by self.battery_control_d already initialized. (never initialize to None)
B: when self.UpdateCurrent and/or the others are updated recreate/update self.battery_control_d.
C: Use a name reference and get the value of that attribute when accessed from self.battery_control_d.
The first two are pretty self explanatory but it seems you are interested in option C so I will expand on it:
You can create a class with several property(ies) that retrieve an attribute from your original object when accessed.
class VarReference(object):
def __init__(self, inst, update_name, get_name, value1, value2):
self.inst = inst
self.update_attr_name = update_name
self.getter_attr_name = get_name
self.value1 = value1
self.value2 = value2
#property
def get(self):
return getattr(self.inst, self.getter_attr_name)
#property
def update(self):
return getattr(self.inst, self.update_attr_name)
class Test(object):pass #dummy class for my demo
self = Test()
self.UpdateCurrent = self.GetCurrent = None
ref_obj = VarReference(self,"UpdateCurrent","GetCurrent",None,1)
>>> print(ref_obj.get)
None
>>> self.GetCurrent = lambda:5
>>> ref_obj.get
<function <lambda> at 0x1057d5488>
>>> ref_obj.get()
5
If you are unfamiliar with property basically the function that it decorates is called when the attribute name is accessed on an instance (and therefore retrieving an attribute of the original instance)
so you would in this case write the initialization for self.battery_control_d like this:
self.battery_control_d = OrderedDict([('Current',VarReference(self, "UpdateCurrent", "GetCurrent", None, 1)),
('Cell Voltage',VarReference(self, "UpdateCellVoltage", "GetCellVoltage", 0, 24)),
('Cell Temperature',VarReference(self, "UpdateCellTemperature", "GetCellTemperature", 0, 24))
])
then self.battery_control_d["current"].get would be the result of getattr(self,"GetCurrent") which is equivalent to self.GetCurrent dynamically.
If you really want to use VALUE[0] and VALUE[1] instead of VALUE.update and VALUE.get then you can just override __getitem__ of the class as well, although I'd highly recommend switching to more verbose solutions:
class VarReference(object):
...
def __getitem__(self,item):
if item==0:
return self.update
elif item == 1:
return self.get
elif item ==2:
return self.value1
elif item == 3:
return self.value2
else:
raise IndexError("Can only get indices from 0 to 3")
I'm working with kivy on python2.7. As far as I know, self is not a real argument but a tool to use in the function, when working with the parent data. Yet in the following use, python thinks self is a real argument. Is this because I'm calling it in the function?
class Verdo(BoxLayout):
defualtval = ""
tarih = StringProperty(str(datetime.datetime.now()).split(".")[0])
istipitxt = StringProperty(defualtval)
iscitxt = StringProperty(defualtval)
iskodtxt = StringProperty(defualtval)
baslabittxt = StringProperty(defualtval)
parcanotxt = StringProperty(defualtval)
def start(self):
Clock.schedule_interval(self.callback, 0.5)
def callback(self, dt):
print "testo"
self.tarih = StringProperty(str(datetime.datetime.now()).split(".")[0])
start()
#Clock.schedule_interval((lambda dt: updater(), 1), 0.5)
#Clock.schedule_interval((lambda dt: tell(), 1), 0.5)
When the code is run, following error happens:
2015-04-07 22:05:03.081739
Traceback (most recent call last):
File "/home/toshy/workspace/Verdo_reborn/main.py", line 28, in <module>
class Verdo(BoxLayout):
File "/home/toshy/workspace/Verdo_reborn/main.py", line 79, in Verdo
start()
TypeError: start() takes exactly 1 argument (0 given)
I also tried an simpler approach which also failed:
def callback(self, dt):
print "testo"
self.tarih = StringProperty(str(datetime.datetime.now()).split(".")[0])
Clock.schedule_interval(callback, 0.5)
output:
ret = callback(self._dt)
TypeError: callback() takes exactly 2 arguments (1 given)
You should be calling:
self.start()
self is a real argument, but it's supplied automatically as the object on which the method was called.
There are two different contexts in which you might want to call .start(). The first is after instantiating an object of type Verdo:
my_verdo = Verdo()
my_verdo.start()
Alternatively, you may be calling from inside the code for Verdo. In that case you need to specify that your're operating on the current instance.
You should do something like this:
class Verdo(BoxLayout):
defualtval = ""
tarih = StringProperty(str(datetime.datetime.now()).split(".")[0])
istipitxt = StringProperty(defualtval)
iscitxt = StringProperty(defualtval)
iskodtxt = StringProperty(defualtval)
baslabittxt = StringProperty(defualtval)
parcanotxt = StringProperty(defualtval)
def start(self):
Clock.schedule_interval(self.callback, 0.5)
def callback(self, dt):
print "testo"
self.tarih = StringProperty(str(datetime.datetime.now()).split(".")[0])
if __name__ == '__main__':
verdoInstance = Verdo()
verdoInstance.start()
This is just an example, if you want test your code quickly as a single executable python script.
Your error was you tried to call your class method without calling constructor right in your class code. In this case method class really was waiting self (object ref) as a first argument, but the object wasn`t created at that time.
I have created a singlton Here is the class description.
allsms.py
from DB.models import ApiKey,ServiceProvider
from DB.messagenet import MessageNet
class SMSMgr( object ):
_instance = None
_allsp = []
def __init__(self):
pass
def __new__(cls, *args, **kwargs):
if not cls._instance :
cls._instance = super(SMSMgr, cls).__new__(
cls, *args, **kwargs)
return cls._instance
def loadsettings(self):
get_all_sp = ServiceProvider.objects.filter(status = False)
for obj in get_all_sp:
cla = obj.class_Name
a=globals()[str(obj.class_Name)](obj.userName,obj.password,obj.sendingurl)
self._allsp.append(a)
#print self._allsp
def reload(self):
self._allsp = []
get_all_sp = ServiceProvider.objects.filter(status = False)
for obj in get_all_sp:
cla = obj.class_Name
a=globals()[str(obj.class_Name)](obj.userName,obj.password,obj.sendingurl)
self._allsp.append(a)
def send(self):
print "+++++++++++++++++++== Global send "
if __name__ == "__main__":
b = SMSMgr()
b.loadsettings()
Now in test.py file of the same directory I am trying to use the singleton object which stored in the _allsp variable like.
from SMShandler.allsms import SMSMgr
b = SMSMgr()
#b.loadsettings()
print b._allsp
This is printing empty list. But when I am doing like this:
b = SMSMgr()
b.loadsettings()
print b._allsp
it is printing the list of objects .
My question is, if the above design is singlton then why print b._allsp is printing empty list in test.py? I am already loading loadsettings in the allsms.py file .
You are running loadsettings() in an if __name__ == "__main__" block:
if __name__ == "__main__":
b = SMSMgr()
b.loadsettings()
The purpose of such a block is to happen only when the code is run directly (like python allsms.py). That means it won't happen when it is imported in the line:
from SMShandler.allsms import SMSMgr
If you put the line b.loadsettings() outside of the if block, you'll see that it will already be loaded.