This is my code.
from multiprocessing.managers import BaseManager
from threading import Thread
def manager1():
my_dict = {}
my_dict['key'] = "value"
print(my_dict['key']) #this works
class SyncManager(BaseManager): pass
SyncManager.register('get_my_dict', callable=lambda:my_dict)
n = SyncManager(address=('localhost', 50001), authkey=b'secret')
t = n.get_server()
t.serve_forever()
def get_my_dict_from_the_manager():
class SyncManager(BaseManager): pass
SyncManager.register('get_my_dict')
n = SyncManager(address=('localhost', 50001), authkey=b'secret')
n.connect()
my_dict = n.get_my_dict()
return my_dict
thread1 = Thread(target=manager1)
thread1.daemon = True
thread1.start()
my_dict = get_my_dict_from_the_manager()
print(my_dict.keys()) #this works
print(my_dict['key']) #DOES NOT WORK
On the last line of the script, I try to access a value in the dictionary my_dict by subscripting with a key. This throws an error. This is my terminal output:
value
['key']
Traceback (most recent call last):
File "/home/magnus/PycharmProjects/docker-falcon/app/so_test.py", line 31, in <module>
print(my_dict['key'])
TypeError: 'AutoProxy[get_my_dict]' object is not subscriptable
Process finished with exit code 1
It seems the AutoProxy object sort of behaves like the dict it is supposed to proxy, but not quite. Is there a way to make it subscriptable?
The problem is that the AutoProxy object does not expose the __getitem__ method that a dict normally has. An answer to my similar question allows you to access items by their key: simply replace print(my_dict['key']) with print(my_dict.get('key'))
Related
I want to start by stating that I am aware that this error message was posted multiple times. But I cannot seem to understand how those posts apply to me. So I want to try my luck:
I have Dataframe "df" and I am trying to perform a parallel processing of subsets of that dataframe:
for i in range(1, 2):
pool = ThreadPool(processes=4)
async_result = pool.apply_async(helper.Helper.transform(df.copy(), i))
lst.append(async_result)
results = []
for item in lst:
currentitem = item.get()
results.append(currentitem)
Helper Method:
#staticmethod
def transform(df, i):
return df
So I usualle code in Java and for a class I need to do some stuff in python. I just dont understand why in this case I get the error:
Traceback (most recent call last):
File "C:/Users/Barry/file.py", line 28, in <module>
currentitem = item.get()
File "C:\Users\Barry\AppData\Local\Programs\Python\Python38-32\lib\multiprocessing\pool.py", line 768, in get
raise self._value
File "C:\Users\Barry\AppData\Local\Programs\Python\Python38-32\lib\multiprocessing\pool.py", line 125, in worker
result = (True, func(*args, **kwds))
TypeError: 'DataFrame' object is not callable
A print in the thread function or before creating the thread results in proper output.
The issue is with the line:
async_result = pool.apply_async(helper.Helper.transform(df.copy(), i))
The catch - you're calling the function 'transform' before passing it to apply_async. As a result, apply async receives a data frame, "thinks" it's a function, and tries to call it asynchronously. The result is the exception you're seeing, and this result is saved as part of the AsyncResult object.
To fix it just change this line to:
async_result = pool.apply_async(helper.Helper.transform, (df.copy(), i))
Note that apply_async gets two arguments - the function and the parameters to the function.
Error
Traceback (most recent call last):
File "C:/Users/RCS/Desktop/Project/SHM.py", line 435, in <module>
app = SHM()
File "C:/Users/RCS/Desktop/Project/SHM.py", line 34, in __init__
frame = F(container, self)
File "C:/Users/RCS/Desktop/Project/SHM.py", line 384, in __init__
if "3202" in q:
TypeError: argument of type 'method' is not iterable
code
some part of code, initialisation and all
while 1:
q = variable1.get
if "3202" in q:
variable2.set("NI NODE3202")
try:
switch(labelframe2, labelframe1)
except:
switch(labelframe3, labelframe1)
elif "3212" in q:
variable2.set("NI NODE3212")
try:
switch(labelframe1, labelframe2)
except:
switch(labelframe3, labelframe2)
elif "3214" in q:
variable2.set("NI NODE3214")
try:
switch(labelframe1, labelframe3)
except:
switch(labelframe2, labelframe3)
else:
None
some other part of code
def switch(x, y):
if x.isGridded:
x.isGridded = False
x.grid_forget()
y.isGridded = True
y.grid(row=0, column=0)
else:
return False
I am trying to create a switch between three labelframes which are inside another labelframe, and outside this labelframe are other labelframes that are not changing.
I have read some similar answers but I don't want to use __iter__() in my code. Can anybody provide any other suggestions?
You forgot to call the Entry.get() method:
q = variable1.get()
# ^^ call the method
Because the method object itself doesn't support containment testing directly, Python is instead trying to iterate over the object to see if there are any elements contained in it that match your string.
If you call the method, you get a string value instead. Strings do support containment testing.
The reason you got that error was because you did not add "()" after.get query hence the error to fix this change q = variable1.get to q = variable.get()
Sorry if this question is stupid. I created an unittest class which needs to take given inputs and outputs from outside. Thus, I guess these values should be initiated. However, I met some errors in the following code:
CODE:
import unittest
from StringIO import StringIO
##########Inputs and outputs from outside#######
a=[1,2]
b=[2,3]
out=[3,4]
####################################
def func1(a,b):
return a+b
class MyTestCase(unittest.TestCase):
def __init__(self,a,b,out):
self.a=a
self.b=b
self.out=out
def testMsed(self):
for i in range(self.tot_iter):
print i
fun = func1(self.a[i],self.b[i])
value = self.out[i]
testFailureMessage = "Test of function name: %s iteration: %i expected: %i != calculated: %i" % ("func1",i,value,fun)
self.assertEqual(round(fun,3),round(value,3),testFailureMessage)
if __name__ == '__main__':
f = MyTestCase(a,b,out)
from pprint import pprint
stream = StringIO()
runner = unittest.TextTestRunner(stream=stream, verbosity=2)
result = runner.run(unittest.makeSuite(MyTestCase(a,b,out)))
print 'Tests run', result.testsRun
However, I got the following error
Traceback (most recent call last):
File "C:testing.py", line 33, in <module>
result = runner.run(unittest.makeSuite(MyTestCase(a,b,out)))
File "C:\Python27\lib\unittest\loader.py", line 310, in makeSuite
return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
File "C:\Python27\lib\unittest\loader.py", line 50, in loadTestsFromTestCase
if issubclass(testCaseClass, suite.TestSuite):
TypeError: issubclass() arg 1 must be a class
Can anyone give me some suggestions? Thanks!
The root of the problem is this line,
result = runner.run(unittest.makeSuite(MyTestCase(a,b,out)))
unittest.makeSuite expects a class, not an instance of a class. So just MyTestCase, not MyTestCase(a, b, out). This means that you can't pass parameters to your test case in the manner you are attempting to. You should probably move the code from init to a setUp function. Either access a, b, and out as globals inside setUp or take a look at this link for information regarding passing parameters to a unit test.
By the way, here is the source file within python where the problem originated. Might be informative to read.
I want to serialize a dictionary to JSON in Python. I have this 'str' object has no attribute 'dict' error. Here is my code...
from django.utils import simplejson
class Person(object):
a = ""
person1 = Person()
person1.a = "111"
person2 = Person()
person2.a = "222"
list = {}
list["first"] = person1
list["second"] = person2
s = simplejson.dumps([p.__dict__ for p in list])
And the exception is;
Traceback (most recent call last):
File "/base/data/home/apps/py-ide-online/2.352580383594527534/shell.py", line 380, in post
exec(compiled_code, globals())
File "<string>", line 17, in <module>
AttributeError: 'str' object has no attribute '__dict__'
How about
s = simplejson.dumps([p.__dict__ for p in list.itervalues()])
What do you think [p.__dict__ for p in list] does?
Since list is not a list, it's a dictionary, the for p in list iterates over the key values of the dictionary. The keys are strings.
Never use names like list or dict for variables.
And never lie about a data type. Your list variable is a dictionary. Call it "person_dict` and you'll be happier.
You are using a dictionary, not a list as your list, in order your code to work you should change it to a list e.g.
list = []
list.append(person1)
list.append(person2)
I have two functions which print into an excel file. THe only input is the file name. Here is the code:
#excelpy
import excelpy
#Tinker
from Tkinter import *
from tkSimpleDialog import *
from tkFileDialog import *
Function Mode1
def Mode1(full_name):
print full_name
print type(full_name)
testwbook = excelpy.workbook(full_name)
testwbook.show()
testwbook.set_cell((1,1),'TEST1', fontColor='red')
testwbook.set_range(2,1,['Number','Name'])
m1 = testwbook.save(full_name)
testwbook.close()
return m1
Function Mode2
def Mode2(full_name):
print full_name
print type(full_name)
testwbook = excelpy.workbook(full_name)
testwbook.show()
testwbook.set_cell((1,1),'TEST2', fontColor='red')
testwbook.set_range(2,1,['Number','Name'])
m2 = testwbook.save(full_name)
testwbook.close()
return m2
Main
root = Tk()
d = str(asksaveasfilename(parent=root,filetypes=[('Excel','*.xls')],title="Save report as..."))
d = d + '.xls'
d = d.replace('/','\\')
root.destroy()
Mode1(d)
Mode2(d)
And once in a while I get the following error:
Traceback (most recent call last):
File "T:\TEST\testpy.py", line 2035, in <module>
Mode2(d)
File ""T:\TEST\testpy.py"", line 1381, in Mode2
print type(full_name)
TypeError: 'str' object is not callable
Any idea why is this happening? How can I prevent it?
The only function call in the line you get the error is a call to the built-in function type(), so the only explanation for your error message is that you overwrote the built-in name type by a global name type pointing to a string object. Try adding
print type
before
print type(full_name)
It looks like somewhere you're setting a (global) variable named type to a string, thus overwriting the built-in type function.
Try searching your code for type = to see what turns up.
Understandably, Python would then throw that exception when you tried to call type (strings can't be "called").