Python exception class not defined, no attribute - python

I am currently using pytesseract which defines an exception class as follows:
class TesseractError(Exception):
def __init__(self, status, message):
self.status = status
self.message = message
self.args = (status, message)
in my main.py, I tried several ways to use this exception for exception handling but I've gotten no "TesseractError" attribute error and no "TesseractError" defined error.
1.
>>> from pytesseract import TesseractError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'TesseractError'
2.
>>> import pytesseract
>>> try: raise pytesseract.TesseractError(True,"True")
... except TesseractError: print("error")
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'pytesseract' has no attribute 'TesseractError'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
NameError: name 'TesseractError' is not defined
3.
>>> import pytesseract
>>> try: raise TesseractError(True,"True")
... except TesseractError: print("error")
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'TesseractError' is not defined
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
NameError: name 'TesseractError' is not defined
However, when I try the following in terminal, it just works.
>>> class ERR(Exception): pass
>>> try: raise ERR()
... except ERR: print("error found")
error found
so it seems it's the importing step is wrong but I don't know what caused it.

Here's the __init__ file:
https://github.com/madmaze/pytesseract/blob/master/src/init.py
Notice that it does not import the TesseractError to be visible from the package itself. You could either change the init file or import from the package>module>
from pytesseract.pytesseract import TesseractError

Related

Running `python -m unittest` changes the way exceptions with overriden `__name__` are printed in the traceback

I have a piece of code that dynamically creates Exceptions. Every exception class created in this way gets its __name__ overwritten:
def exception_injector(name, parent, module_dict):
class product_exception(parent):
pass
product_exception.__name__ = name
product_exception.__module__ = module_dict["__name__"]
module_dict[name] = product_exception
When I use it regularly it prints everything out just fine:
>>> namespace = {"__name__": "some.module"}
>>> exception_injector("TestError", Exception, namespace)
>>> raise namespace["TestError"]("What's going on?")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
some.module.TestError: What's going on?
But when I use the unittest module the original __name__ is printed:
>>> import unittest
>>> class DemoTestCase(unittest.TestCase):
... def test_raise(self):
... namespace = {"__name__": "some.module"}
... exception_injector("TestError", Exception, namespace)
... namespace["TestError"]("What's going on?")
...
>>> unittest.main(defaultTest="DemoTestCase", argv=["demo"], exit=False)
E
======================================================================
ERROR: test_raise (__main__.DemoTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "<stdin>", line 3, in test_raise
some.module.exception_injector.<locals>.product_exception: What's going on?
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (errors=1)
<unittest.main.TestProgram object at 0x1017c3eb8>
From where on the exception object could the unittest module be getting this original information?
Unittests use the traceback module to format exceptions. You can reproduce your output by doing the same:
>>> import traceback
>>> try:
... raise namespace["TestError"]("What's going on?")
... except Exception as e:
... tb = traceback.TracebackException.from_exception(e)
... print(*tb.format())
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
some.module.exception_injector.<locals>.product_exception: What's going on?
What is being printed is the object __module__ attribute value*, with object.__qualname__ attribute appended (with a dot separator), rather than __module__ plus __name__:
>>> namespace["TestError"].__qualname__
'exception_injector.<locals>.product_exception'
The qualified name includes the full scope where the class was created (function names here, but this could also include class names).
If your aim is to add exceptions to the global namespaces of a module, you can just set it to the same value as name:
>>> namespace["TestError"].__qualname__ = "TestError"
>>> try:
... raise namespace["TestError"]("What's going on?")
... except Exception as e:
... tb = traceback.TracebackException.from_exception(e)
... print(*tb.format())
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
some.module.TestError: What's going on?
or in the context of your code:
def exception_injector(name, parent, module_dict):
class product_exception(parent, details=args):
pass
product_exception.__name__ = name
product_exception.__qualname__ = name
product_exception.__module__ = module_dict["__name__"]
module_dict[name] = product_exception
* The traceback module omits the exception module if the module name is either __main__ or builtins.

Python try except - Include the custom message in the Error variable

Im trying to do a simple try except, and it is working. But I want to add some custom string at the beginning of the error message. If I just add it in print, its giving error.
import sys
try:
with open('./datatype-mapping/file.json') as rs_mapping:
data_mapping = json.load(rs_mapping)
except Exception as error:
print('CUSTOM ERROR: '+error)
sys.exit(1)
The error I got is,
Traceback (most recent call last):
File "c:/Users/rbhuv/Desktop/code/bqshift.py", line 22, in get_datatype_mapping
with open('./datatype-mapping/file.json') as rs_mapping:
FileNotFoundError: [Errno 2] No such file or directory: './datatype-mapping/file.json'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:/Users/rbhuv/Desktop/code/bqshift.py", line 102, in <module>
main()
File "c:/Users/rbhuv/Desktop/code/bqshift.py", line 99, in main
target_mapping()
File "c:/Users/rbhuv/Desktop/code/bqshift.py", line 39, in target_mapping
data_mapping = get_datatype_mapping()
File "c:/Users/rbhuv/Desktop/code/bqshift.py", line 26, in get_datatype_mapping
print('ERROR: '+error)
TypeError: can only concatenate str (not "FileNotFoundError") to str
But if I use just print(error) - this is working.
You need to convert error to str.
import sys
try:
int("fail")
except Exception as error:
print('CUSTOM ERROR: ' + str(error))
sys.exit(1)
This works flawlessly.

Python catching entry exception with decimal.InvalidOperation

I'm working an exception example copied from a book.
from decimal import *
entry=input("GRD Conversion")
try:
grd_usd=Decimal(entry)
except decimal.InvalidOperation:
print("Invalid: ",entry)
Instead of the expected error of Invalid: 3d for 3d as my entry I get
Traceback (most recent call last): File
"/Users/myuser/Library/Preferences/IdeaIC2018.1/scratches/scratch.py",
line 6, in
grd_usd=Decimal(entry) decimal.InvalidOperation: []
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File
"/Users/myuser/Library/Preferences/IdeaIC2018.1/scratches/scratch.py",
line 7, in
except decimal.InvalidOperation: NameError: name 'decimal' is not defined
I'm using Python 3.6 on a Mac.
As the error suggests, you have nothing named decimal. When using from .. import *, the package itself does not become a variable. Then it is impossible to find decimal.InvalidOperation
import decimal
entry = input("GRD Conversion")
try:
grd_usd = decimal.Decimal(entry)
except decimal.InvalidOperation:
print("Invalid: ", entry)

Python: accessing exception message of original exception

I have the following two functions:
>>> def spam():
... raise ValueError('hello')
...
>>> def catch():
... try:
... spam()
... except ValueError:
... raise ValueError('test')
Trying to catch the second ValueError exception works just fine and prints the exception's error message:
>>> try:
... catch()
... except ValueError as e:
... print(e)
...
test
Is there however any way to access the original exception's error message (i.e. 'hello')? I know I can print the full traceback with:
>>> try:
... catch()
... except ValueError as e:
... import traceback
... print(traceback.format_exc())
...
Traceback (most recent call last):
File "<stdin>", line 3, in catch
File "<stdin>", line 2, in spam
ValueError: hello
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 5, in catch
ValueError: test
but I don't exactly want to parse the hello from that string. Is there a way to access the list of exceptions and their respective messages, from which I would simply take the first one?
Figured it out: the original exception is available via e.__cause__.

NameError: global name 'imfilter' is not defined

I am trying to use imfilter and, despite of upgrading to 0.18.1 version, I cannot use it:
>>> import scipy
>>> blurred_arr = scipy.imfilter(arr, "blur")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'imfilter'
>>> blurred_arr = scipy.misc.imfilter(arr, "blur")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'misc'
>>> blurred_arr = imfilter(arr, "blur")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'imfilter' is not defined
>>> scipy.__version__
'0.18.1'
I am not an expert in Python, so I feel that I am asking something really silly here...Can you help please?
If scipy.misc is its own module, then it has to be imported explicitly.
Either:
import scipy.misc
...
scipy.misc.imfilter(...)
or
from scipy.misc import imfilter
...
imfilter(...)

Categories

Resources