Is there any way, how to find out line of code, where I called: raise MyError("something")??
I have code like this:
class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
Can I get the line of exception in this class?
Calling like this:
try:
somethin()
except:
raise MyError("abc")
Thank you
You should be able to use traceback for this.
Related
I am writing a code that has a class Fraction with attributes Numerator and Denominator. The Output should display the fraction in a simplified form. For e.g. 20/100 should be display as 1/5.
I have tried the below code but getting a Type Error as below:
TypeError: unsupported operand type(s) for /: 'int' and 'NoneType'
class fraction:
def get_data(self):
self.__num=int(input("Enter the Nr:"))
self.__deno=int(input("Enter the Dr:"))
if (self.__deno==0):
print("Fraction not possible")
exit()
def display_data(self):
self.__simplify()
print(self.__num,"/",self.__deno)
def __simplify(self):
print("The simplified fraction is")
common_divisor=self.__GCD(self.__num,self.__deno)
self.__num=(self.__num)/(common_divisor)
self.__deno=(self.__deno)/(common_divisor)
def __GCD(self,a,b):
if (b==0):
return a
else:
self.__GCD(b,a%b)
f=fraction()
f.get_data()
f.display_data()
I have no clue how to solve this Error. Please help me as i am new to Python and want to build strong basics.
The problem is in this function definition:
def __GCD(self,a,b):
if (b==0):
return a
else:
self.__GCD(b,a%b)
There's no return statement on the else clause. (Also, the else clause can be implicit instead of explicit.) Instead try:
def __GCD(self, a, b):
if b == 0:
return a
return self.__GCD(b, a % b)
this is my code stuff where i am getting error ,
when i am going to execute it
i want to create custom middleware .
from marketing.models import MarketingMessage
class DisplayMarketing():
def process_request(self,request):
try:
request.session['marketing_message']=MarketingMessage.objects.all()[0].message
except:
request.session['marketing_message']=False
you can try following implimentation
from django.utils.deprecation import MiddlewareMixin
class DisplayMarketing(MiddlewareMixin):
def process_request(self, request):
try:
request.session['marketing_message']=MarketingMessage.objects.all()[0].message
except:
request.session['marketing_message']=False
I have a function, that should do report, if test function success.
But, I don't want to do report, if there is an Exception inside test function.
I try to use pytest.fixture, pytest.yield_fixture, but all of them always call finalizers. How can I understand, that Exception had been raised in test function?
test.py StatisticClass: start
FStatisticClass: stop
finalizer
contest of test.py:
#pytest.mark.usefixtures("statistic_maker")
def test_dummy():
raise Exception()
content of conftest.py:
class StatisticClass():
def __init__(self, req):
self.req = req
pass
def start(self):
print "StatisticClass: start"
def stop(self):
print "StatisticClass: stop"
def if_not_exception(self):
"""
I don't want to call this if Exception inside yield.
Maybe, there is any info in request object?
"""
print "finalizer"
#pytest.yield_fixture(scope="function")
def statistic_maker(request):
ds = StatisticClass(request)
ds.start()
request.addfinalizer(ds.if_not_exception)
yield
ds.stop()
P.S. I can't use decorator because, I use fixture.
I'm having some troubles due to the changes to dict.values() and keys() in Python3.
My old code was something like this:
import json
class ComplexEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, complex):
return [obj.real, obj.imag]
return json.JSONEncoder.default(self, obj)
a = { '1' : 2 + 1j, '2' : 4 + 2j }
print(json.dumps(a.values(), cls=ComplexEncoder))
This on Python 3.3+ raise the exception:
TypeError: dict_values([(2+1j), (4+2j)]) is not JSON serializable
The easy workaround is to do list(a.values()), the problem for me is that I have a lot instances like that in the code. Is there a way to extend the ComplexEncoder in order to iterate over the
view?
You could encode the iterable as a list:
class IterEncoder(json.JSONEncoder):
def default(self, obj):
try:
return list(obj)
except TypeError:
return super().default(obj)
class ComplexEncoder(IterEncoder):
def default(self, obj):
if isinstance(obj, complex):
return [obj.real, obj.imag]
return super().default(obj)
Let's say I have this virtual E-library and I have a function defined under a class that allows me to check if a book is in a given library BY ID NUMBER OF THE BOOK (which is an object) and if it isn't, I append it to the library. If I test it in a try-except block I keep getting the except message even though I know the ID number doesn't already exist. If someone can help me figure out this problem that would be good.
class Library:
# the class constructor
def __init__(self, books, patrons):
self.books=books
self.patrons=patrons
def __str__(self):
s="Patron("
for patron in self.patrons:
s+=str(patron) + ', '
if len(self.patron) != 0:
s= s[:-2]
s+=']'
for book in self.books:
s+=str(book) + ', '
if len(self.books) != 0:
s= s[:-2]
s+='])'
return s
def __repr__(self):
return str(self)
def donate_book(self, book):
for i in self.books:
if i==book.book_id:
raise DuplicateIdError()
else:
Library.append(book)
This is my try-except block:
try:
donate_book(book)
print("Thank you for your Donation!")
except:
print ("that id# is already taken, sorry")
my library was defined as an empty list
library=[]
is my try-except block code wrong or is my donate_book code wrong?
my Book class:
class Book:
# the class constructor
def __init__(self, author, title, book_id):
self.title = title
self.author = author
self.book_id = book_id
def __str__(self):
s = "Books("+self.author+", "+self.title+", "+self.book_id+")"
return s
def __repr__(self):
return str(self)
I defined duplicate error as this:
class DuplicateIdError(Exception):
#the class constructor
def __init__(self, ident):
self.ident= ident
def __str__(self):
s= print("'duplicate identificatoin: #" + self.ident + ".'")
return s
# returns a string rep matching
def __repr__(self):
return str(self)
I think you would like to use:
if i.book_id == book.book_id:
in your donate_book() method.
Redefine your donate_book method like this:
def donate_book(self, book):
if book in self.books:
raise DuplicateIdError()
else:
self.books.append(book)
In the Book class, define this method:
def __eq__(self, other):
return self.book_id == other.book_id
This overrides the equality test between books.