I am working with a method that is used within a larger script that is used to log information to a queue with a fallback to print the message to the console if the queue has not been created.
def _log(self, msg):
if self.queue:
self.queue.put(msg)
else:
print(msg)
However when I use the code in a separate script that I have made to test my understanding of its functionality I get an error.
import queue
class Thing:
def __init__ (self, num1, num2):
self.num1 = num1
self.num2 = num2
def _log(self, msg):
if self.queue:
self.queue.put(msg)
else:
print(msg)
def add(self):
self._log(self.num1 + self.num2)
test1 = Thing(1,2)
test1.add()
AttributeError: 'Thing' object has no attribute 'queue'
My understanding of this code is that if no queue has been initialized then the log should print to the console instead? Why is that not the case?
6
The error is explained pretty simply. Thing has no attribute “queue”. The interpreter cannot find it and so breaks. If you used “try, except” then if the code within the try would normally break, then the except runs and if it works, the try bit runs. This is a good way to do what you want if I am understanding correctly. I have entered an example of this use below.
try:
this will break
except:
print("and yet this will still run")
I hope I understood your problem right and this helps.
2