calling one python object from another - python-3.x

I have two different modules (files) where I store different objects.
The work flow is - call objects from different files and return the values from the database. If I call object from file_1 below, it returns required values from the database. However when I call object from file_1 in file_2, it returns 'None' even though input parameter is supplied.
file_1
class Database(object):
database = None
host = None
port = None
def __init__(self, host=None, port=None):
self.host=None
self.port=None
def client_(self):
return MongoClient()
def find_spefic_director(self, db=None, coll=None, directorId=None):
'''If when a specific director id is supplied it returns director related information'''
project={'_id': 0}
filter={'directorid': directorId}
print(directorId)
if not directorId is None:
result = self.client_()[db][coll].find(projection=project,
filter=filter)
return [i for i in result]
else:
return 'valid Id is required'
if __name__ == "__main__":
Database()
file_2
class Graph(object):
def __init__(self, host=None, port=None):
self.host=None
self.port=None
self.directorId=None
def minMaxDate(self, db=None, coll=None, directorId=None):
dr= Database(self.host, self.port).find_spefic_director(self.directorId)
drt=dr(directorId)
return drt
if __name__ == "__main__":
Graph()
Now I am trying to call Database() in file 2 for further processing in a different file
from file_1 import Database
from file_2 import Graph as gc
gc(directorId=340769.0).minMaxDate(db, coll='directory', directorId=340769.0)
when I run, it returns
None
TypeError Traceback (most recent call last)
<ipython-input-3-2d56a89c0288> in <module>
----> 1 gc().minMaxDate(db, coll='crsp_na_wrds_company_director_names', directorId=340769.0)
~/graph_construct.py in minMaxDate(self, db, coll, directorId)
25
26 dr= Database(self.host, self.port).find_spefic_director(self.directorId)
---> 27 drt=dr(directorId)
28
29
TypeError: 'str' object is not callable
What should be done to return the values stored in the database?

Related

Getting unexpected NoneType error in Python

While trying to create a minimal, reproducible example for another problem in Python 3.7.3, I ran into a NoneType Error that I wasn't expecting.
Main program:
import worker
def multiply_worker_value(arguments):
current_Worker = arguments[0]
multiplier = arguments[1]
new_worker = current_Worker.change_value(multiplier)
return new_worker
current_worker = worker.Worker()
print("Printing value:")
print(current_worker.get_value()[0])
while(current_worker.get_value()[0] < 10):
paramList = [current_worker,2]
current_worker = multiply_worker_value(paramList)
print(current_worker.get_value()[0])
Worker class:
import numpy
class Worker():
def __init__(self):
self.values = numpy.random.rand(10)
def change_value(self,multiplier):
self.values = numpy.sum(self.values*multiplier)
def get_value(self):
return self.values
When this is run, I get:
Printing value:
0.10619190084595542
Traceback (most recent call last):
File "F:\Visual Studio\repos\Projects2020\tests\concurrent_test\concurrent_test\main.py", line 14, in <module>
while(current_worker.get_value()[0] < 10):
AttributeError: 'NoneType' object has no attribute 'get_value'
Press any key to continue . . .
and I am not sure why this is happening.
Inside the while loop, your current_worker gets overwritten with None:
current_worker = multiply_worker_value(paramList)
this calls:
new_worker = current_Worker.change_value(multiplier)
Your Worker.change_value method does not have a return statement, so it implicitly returns None.
Then, in the second iteration of your loop, your code tries to call get_value on None, which fails.

Python will not open a module within my .py file

I was working on some code which retrieves a line in a text file ("save[#]) with the format:
"[name],[boolean or integer value]"
(The aim is to be able to retrieve it for save states of a game)
The issue is that whenever I try to return a value from my module I get the following:
Traceback (most recent call last):
File "//IHS-FS-001.ihs.local/Cohort2020$/2ELGAG1/python/srctg/test.py", line 5, in <module>
retrieve()
File "//IHS-FS-001.ihs.local/Cohort2020$/2ELGAG1/python/srctg/test.py", line 3, in retrieve
if retrieve.check("test", 1) == True:
AttributeError: 'function' object has no attribute 'check'
The test attribute is a testing module set up to test the code for the game:
import retrieve.py
def retrieve():
if retrieve.check("test", 1) == True:
return True
retrieve()
The retrieve attribute itself is set up like so:
import error
def check(i_name, save):
save = str(save)
save_n = "save" + save + ".txt"
save_f = open(save_n, "r")
list = save_f.readlines()
for item in range(len(list)):
list[item] = list[item].strip()
list[item] = list[item].split(",")
list[item][1] = list[item][1]
for item in range(len(list)):
if i_name == list[item][0]:
i_return = list[item][1]
if bool_check(i_return) == True:
i_return = bool(i_return)
elif int_check(i_return) == True:
i_return = int(i_return)
else:
print(error.code("001"))
return "error"
return i_return
def int_check(value):
while True:
try:
value = int(value)
return True
break
except ValueError:
return False
break
def bool_check(value):
while True:
try:
value = bool(value)
return True
break
except ValueError:
return False
break
Don't include the .py in the import. This tries to import a module named py inside the package named retrieve, which is probably not what you meant.
import retrieve as retrieve_module
def retrieve():
if retrieve_module.check("test", 1) == True:
return True
Also, don't write a function with the same name as the module you just imported. Change the name of one or the other. That's why it can't find the .check attribute. It's looking inside the retrieve function instead of inside the retrieve module because you overwrote it in the global namespace (by executing the function definition) before you called the function.

Insert function for bst not working

If anyone can help me with the recursion part?
I omitted some part thnking that it was not necessary but after that function didn't work.
class node(object):
def __init__(self,value):
self.data=value
self.left=None
self.right=None
def insert(Node,value):
if Node is None:
Node=node(value)
else:
if value<Node.data:
## if Node.left is None: Node.left=node(value)
## else: insert(Node.left,value)
insert(Node.left,value)
else:
## if Node.left is None: Node.left=node(value)
## else: insert(Node.left,value)
insert(Node.right,value)
Because you'll need to create new node instances for your empty branches.
Let's see what happens with both definitions, printing out the values of the Node parameter:
def insert(Node, value):
print(Node)
if Node is None:
Node=node(value)
else:
if value<Node.data:
insert(Node.left,value)
else:
insert(Node.right,value)
On the REPL:
In [17]: badTree = node(10)
In [18]: badTree.data
Out[18]: 10
In [20]: badTree.left.data
----------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-20-3cb52def2967> in <module>()
----> 1 badTree.left.data
AttributeError: 'NoneType' object has no attribute 'data'
In [21]: badTree.right.data
----------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-21-b6f1267c9d29> in <module>()
----> 1 badTree.right.data
AttributeError: 'NoneType' object has no attribute 'data'
Let's see what happens if we insert an element to badTree:
In [22]: insert(badTree, 2)
<__main__.node object at 0x7f706bf34d30>
None
In [23]: badTree.left.data
----------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-23-3cb52def2967> in <module>()
----> 1 badTree.left.data
AttributeError: 'NoneType' object has no attribute 'data'
It fails to insert the element, but why? In badTree, both left and right branches are None (empty), what means that we need to create new trees there as we won't be able to recursively add new values, as we lose the reference to the main Node. This is, if we call insert(Node.left, value) before assigning a new object to Node.left, it will be equivalent to call insert(None, value) (this the value None, you can see it when we called insert on badTree), which will call recursively to insert and execute None = node(value) which will do nothing.
What happens if we use this definition instead:
def insert(Node, value):
print(Node)
if Node is None:
Node = node(value)
else:
if value < Node.data:
if Node.left is None:
Node.left = node(value)
else:
insert(Node.left, value)
else:
if Node.right is None:
Node.right = node(value)
else:
insert(Node.right, value)
On the REPL:
In [25]: newTree = node(4)
In [26]: insert(newTree, 10)
<__main__.node object at 0x7f706bf30668>
In [27]: insert(newTree, 12)
<__main__.node object at 0x7f706bf30668>
<__main__.node object at 0x7f706bf30a58>
Now see that it doesn't fail anymore, as we are keeping track of the memory addresses in the tree nodes and thus we can reference those objects (trees) which will let us do the insertions in-place.

AttributeError when monkey patching an object in python

I tried to monkey patch an object in Python.
class C:
def __init__(self):
self.__n = 0
def f(self):
self.__n += 1
def __str__(self):
return str(self.__n)
c = C()
def up(self):
self.__n += 2
import types
c.up = types.MethodType(up, c)
c.up()
But I got an AttributeError
Traceback (most recent call last):
File "untitled4.py", line 19, in <module>
c.up()
File "untitled4.py", line 15, in up
self.__n += 2
AttributeError: 'C' object has no attribute '__n'
How can I fix the error?
As your up function isn't declared inside a class, it is not possible to apply name mangling rules to its locals, while it is applied for the attribute name. Therefore you'd need to apply the name mangling manually in your function:
def up(self):
self._C__n += 2

AttributeError: 'MainWindow' object has no attribute 'dev'

Hy,
Yeah so, i am writing an python3 programm, that should send the content of an file to an LPC1758.
For testing i will write a simple string above USB. I use libusb1.0 ....
But every time i become the same error, even if i rename "dev" into "device" the error is the same.
--> AttributeError: 'MainWindow' object has no attribute 'dev'<--
class MainWindow(QtGui.QMainWindow, form_class):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.pb_send.clicked.connect(self.pb_send_clicked)
self.pb_open.clicked.connect(self.pb_open_clicked)
self.pb_exit.clicked.connect(self.pb_exit_clicked)
# SEND button event handler
def pb_send_clicked(self):
send = "Yo Man"
bulk_out_ep = 0x05
bulk_in_ep = 0x82
interface = 0
length = 30
dev = usb.core.find(idVendor= 0xfefe, idProduct= 0x0001)
cfg = usb.control.get_configuration(dev) # get current configuration
print(dev)
if dev is None:
self.USB_label.setText("Device not found !!!")
raise ValueError('Device not found')
else:
self.USB_label.setText("Device found")
found = 1
if(cfg != 1): # check if device is configured
usb.DeviceHandle.setConfiguration(self, 1)
usb.util.claim_interface(dev, interface)
usb.DeviceHandle.bulkWrite(self,bulk_out_ep,send)
print("wrote to estick")
readData = usb.DeviceHandle.bulkRead(self, bulk_in_ep, length)
print("read from estick: "+ readData)
usb.util.release_interface(dev, interface)
This is what Stacktrace shows:
Traceback (most recent call last):
File "/home/user/workspace_Qt/ESS_project/ess_project.py", line 93, in pb_send_clicked
readData = usb.DeviceHandle.bulkRead(self,endpoint=bulk_in_ep,size=length)
File "/usr/lib/python3.3/usb/legacy.py", line 159, in bulkRead
return self.dev.read(endpoint, size, self.__claimed_interface, timeout)
AttributeError: 'MainWindow' object has no attribute 'dev'
dev is a member of the class DeviceHandle which is the type of the first parameter expected by the setConfiguration functions.
And setConfiguration expects 2 parameters instead of 1, because you are calling the method on the class usb.DeviceHandle instead of calling it on an object of type usb.DeviceHandle, you should use:
dev.setConfiguration(1)
(same thing for bulkWrite and bulkRead).
Also the get_configuration method returns a Configuration object instead of a number, so cfg != 1 will always be true (this may work with cfg.index != 1 instead but I'm not sure).

Resources