DevOps | Cloud | Analytics | Open Source | Programming

Common Python Errors and Fixes Compilation

In this post , we will see & Fix - Common Python Errors. Python is one of the most widely adopted language now. It is interesting to learn & there are plenty of application opportunities for it - be it Data Science, Data Analytics, Automation, Scripting, Web Backend etc. So we will explore the various Python Errors that we face day to day and their fixes and solutions in a short and succinct manner.  

  • TypeError: must be str, not int

>>> '1'+1     -----> char + num

It means you are trying to apply an operation or a  function to something you shouldn't i.e. to something of inappropriate type. In this case , doing addition between a "string" type and a Number !  

  • ImportError:

>>> from x import test
>>> import test
ImportError: cannot import name 'test'

Reason for the error - 'test'  module is not installed , It is not part of the python default packages No user-defined function named as 'test' So cross-check if it is the case for you.  

  • AssertionError:
Assert statement allows to generate simple debug messages or outputs from a logical assertions. If these asserts fails , an AssertionError is raised. Assert statement is generally for unit-testing or finding bugs in the development. However, raising an AssertionError means that the error will be raised by the code, and can be dealt by it's calling processes as needed.

assert_stmt ::= "assert" expression ["," expression]

if __debug__:
if not expression: raise AssertionError

  • AttributeError:
This happens when you don't import the attribute (from a module) but trying to use the attribute in the code.  Because sometimes sub-modules don't automatically get imported .

import A

matrix = A.aa(<some_arguments>)

AttributeError: 'A' object has no attribute 'aa'

  • EOFError:
Raised when input() in Python3 and raw_input() in Python2 function reaches end-of-file condition (EOF) - But no data is given when calling input or raw_input

$ python -c 'input()' < /dev/null
Traceback (most recent call last):
File "<string>", line 1, in <module>
EOFError: EOF when reading a line

except EOFError:
print('Caught EOFError')


Floating point exceptions can be due to - Division by zero , Large Result( Too Large to be expressed) or Invalid operation(Inexpressible result like NaN )

import numpy as np

>>> with np.errstate(invalid='raise'):
... np.sqrt(-1)
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
FloatingPointError: invalid value encountered in sqrt

Hope this helps.  

Other Good Reads -

python error,attributeerror , FloatingPointError , EOFError , AssertionError , ImportError , TypeError