2

I am reading from an sqlite3 database and filtering out NoneType, since I only want values which are not None. I tried both methods suggested here, with identical results. This leads me to think that the below if-statement is correct, but I am missing something more fundamental. Any suggestions are appreciated.

Reading from Databse

        conn.commit()
        c.execute("SELECT tact FROM LineOEE03 ORDER BY tact DESC LIMIT 1")
        current_tact = c.fetchone()

NoneType test

        if current_tact is not None:
            current_tact = int(current_tact[0])
        else:
            current_tact = 60

Error

current_tact = int(current_tact[0])

TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

  • Why am I getting this error if I am specifically tageting not None types in my if-statement?
  • What is the correct way to do this, such when the value is None I can assign a pre-defined value?
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
rrz0
  • 2,182
  • 5
  • 30
  • 65

1 Answers1

3

You can either add an additional test to check if the first item in the list is not None, which is what you're actually trying to convert to an integer:

if current_tact is not None and current_tact[0] is not None:
    current_tact = int(current_tact[0])

or use a try-except block to avoid having to test at all:

try:
    current_tact = int(current_tact[0])
except TypeError:
    current_tact = 60
blhsing
  • 91,368
  • 6
  • 71
  • 106