python object attribute randomly deleting itself - python

i have a problem with python objects where i am creating and iterating over many objects simultaneously.
objects are always created with the correct attributes, but when i iterate over those objects, i check for a certain attribute in the object, this specific attribute randomly gets deleted from the object and then i get an error that the object does not have this attribute.
code:
dead_list = []
for key, trackable_vehicle in self.lane_vehciles.items():
if trackable_vehicle.vehicle_status == 'DEAD' :
dead_list.append(key)
for key in dead_list:
save_object(trackable_vehicle.vehicle_type+'_'+str(trackable_vehicle.object_ID), trackable_vehicle)
self.lane_vehciles.pop(key, None)
Error: 'TrackableTruck' object has no attribute 'vehicle_status'
please note that this code works for me 95% of the time, and this happens for random objects although all objects has the same structure.
after a lot of debugging i just cant get my head around why this happens. the object is correctly created and if i print it before iteration it does have the "vehicle_status" attribute but after iteration the attribute disappears from the object
for example:
object at creation:
{"object_ID": 55, "vehicle_type": "truck", "OTS": "2020-03-10 16:07:16", "lane_ID": 2.0, "vehicle_status": "ALIVE"}
object after iteration:
{"object_ID": 55, "vehicle_type": "truck", "OTS": "2020-03-10 16:07:16", "lane_ID": 2.0}
i hope someone with better knowledge at python than myself can help me.
thanks
EDIT object definition:
class TrackableTruck:
def __init__(self, object_ID, vehicle_type, OTS, lane_ID, vehicle_status):
# info from tracking server
self.object_ID = object_ID
self.vehicle_type = vehicle_type
self.OTS = OTS
self.lane_ID = lane_ID
self.vehicle_status = vehicle_status
code to check and change vehicle status:
d = pickle.loads(full_msg[self.HEADERSIZE:])
d = json.loads(d)
vehicle_type = str(d['vehicle_type'])
vehicle_lane = int(d['lane_ID'])
vehicle_id = int(d['object_ID'])
vehicle_status = d['vehicle_status']
if vehicle_lane == 1:
trackable_vehicle = self.streetLane_1.get_vehicle(vehicle_id)
if trackable_vehicle is None:
self.streetLane_1.add_vehicle(d)
else:
trackable_vehicle.vehicle_status = 'DEAD'
object creation code:
def object_decoder(self,json_obj):
return TrackableTruck(int(json_obj['object_ID']), json_obj['vehicle_type'], json_obj['OTS'], json_obj['lane_ID'], json_obj['vehicle_status'])
def add_vehicle(self, json_obj):
trackable_vehicle = self.object_decoder(json_obj)
self.lane_vehciles[int(trackable_vehicle.object_ID)] = trackable_vehicle

Related

count the sales of a worker

I am trying to count the sales made by a worker but I get the following error when using the code mentioned below:
TypeError: object of type 'bool' has no len()
class Movement_type (models.Model):
_name = 'project_rc.movement_type'
_rec_name = 'movement_type'
type_movement = fields.Selection ([('purchase', 'Purchase'), ('sale', 'Sale'), ('merma', 'Merma')], string = "Movement type", required = True)
class Worker (models.Model):
_name = 'project_rc.worker'
_rec_name = 'name'
sales_counter = fields.Integer (string = "Sales made", compute = "get_sales_realized", store = True)
#api.depends('move_type_ids')
def get_sales_realized (self):
for rec in self:
rec.count_sale = len (rec.move_type_ids.mov_type == 'sale')
I'm not familiar with whatever framework you are using, but if you look at the error you are getting you can see that it is correct.
On line 3, you write rec.move_type_ids.mov_type == 'sale'. It doesn't matter what rec.move_type_ids.mov_type is, when you compare it to something with ==, the answer will either be True or False. It doesn't make sense to take the length of a boolean (t/f).
From the context, I'm guessing that rec.move_type_ids is a list of objects and you want to figure out how many of them have a mov_type property equal to 'sale'. If that's the case, then you could easily do that with a for loop:
sales = []
for thing in rec.move_type_ids:
if thing.type == 'sale':
sales.append(thing)
rec.count_sale = len(sales)
If you want to get a little fancier, you can do that with a filter function:
rec.count_sale = len(filter(lambda x: x.mov_type == 'sale', rec.move_type_ids))

python check if str is in a list of objects

I have a class. In short, to initialize you have to provide it with some values when you create it:
class Silo:
def __init__(self, id, name, netid, node):
self.id = id
self.name = name
self.node = node
self.netid = netid
I may have more than one Silo and they are dynamically created by way of an sqllite database. For clarity's sake I've forgone the code for the database queries and instead printed the list of silos below in my example:
global siloList # siloList is a list of the Silos objects.
siloList = {} # Initialize
print(silos) # return: [(1, 'Silo 1', 1, 1), (2, 'Silo 2', 1, 4)]
for silo in silos: # loop through silos for each silo
newSilo = Silo(silo[0], silo[1], silo[2], silo[3]) # Create the object from Silo class
siloList[silo[0]] = newSilo # Create a list for each Silo object with the ID as the index
I would like to retrieve the ID for each object based on the name I enter so that I can do things with that class.
For example:
userInput = "Silo 2"
# Obtain "2" based on input "Silo 2" somehow
siloList[2].netid = 9 # Change the netid with siloList[id]
I can't figure out how to obtain the id of that object from a name appearing in it, though.
I found a silo = next((x for x, obj in enumerate(siloList) if obj['name'] == userInput), None) but this gives me an error TypeError: 'int' object is not subscriptable and I can't quite figure out how to make it work for my needs (or even if it will work or whatelse would be better).
Thanks.
You can get a list of the matching Silo's IDs with
matching_silo_ID_list = list(id_ for id_ in siloList if siloList[id_].name == userInput)
If you are sure that the matching list has exactly one element you can then safely use
matching_ID = matching_silo_ID_list[0]
to do
siloList[matching_ID].netid = 9
NB. I guess your siloList = {} is actually a dictionary.

Getting this "Attribute error" over and over in python

Can anyone explain why this keeps happening to me?
class TourAgency:
def __init__(self):
self._tours = {}
self._scheduledtours = {}
self._customers = {}
self._booking = {}
def addTour(self,code,tour):
self._tours[code] = tour
def addscheduledtours(self,code,scheduledtour):
self._scheduledtours[code] = scheduledtour
def addCustomer(self,code,customer):
self._customers[code] = customer
def addBooking(self,bookingId,booking):
self._booking[bookingId] = booking
def searchscheduledtours(self,code):
if code in self.scheduledtours.keys():
return self._scheduledtours[code]
else:
return None
mytour = TourAgency()
t1 = Tour("KO111","Discover Korea",8,7,1449.36)
print(t1)
ta = mytour.addTour('KO111',t1)
print(TourAgency.tours)
I get an error saying:
print(TourAgency.tours)
AttributeError: type object 'TourAgency' has no attribute 'tours'
Your class hasn't got the tours attribute, it has only got the _tours attribute. Maybe you want to use it instead.
Remember that, in Python, if an attribute name starts with an underscore, it means that the attribute should be private and not intended to be used by the user.
I hope this could help you! Cheers!

"List object is not callable" error when using Property method in Class

I'm using property method in class to get a subset of user's input:
class deck:
def __init__(self, card_list):
self.cards = card_list
self.cards_slice = []
def get_deal_card(self):
return self.cards_slice
def set_deal_card(self, count):
if count > len(self.cards):
raise Exception("Process failed. Out of index.")
else:
self.cards_slice = self.cards.pop(count)
deal_card = property(get_deal_card, set_deal_card)
d1 = deck([['A',1],['B',1]])
d1.deal_card(0)
It returns type error "List object is not callable". I know this error occurs when I previously defined a list with a name that I used somewhere else. However I still can't see what I do wrong in this program.
Thanks!

table.dataChanged(index, index).connect(someFunction) fails

table = QTableView()
model = QStandardItemModel()
table.setModel(model)
r = table.model().rowCount()
c = table.model().columnCount()
tLeft = table.model().index(0, 0)
bRight = table.model().index(r, c)
table.dataChanged(tLeft, bRight).connect(SomeFunction)
AttributeError: 'NoneType' object has no attribute 'connect'
Goal - to call SomeFunction when one of the items was changed directly by user in QTableView().
What do I do wrong? I see that NoneType object cannot has attribute connect, but why it is NoneType.
Please comment. I am a beginner. Qt5.
You should do:
table.model().dataChanged.connect(someFunction)
# or model.dataChanged.connect(someFunction)
No need to precise the arguments. The slot should look like this:
def someFunction(tLeft,bRight):
#do stuff

Categories

Resources