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?
4
  • 1
    is current_tact = [None] (or a list/tuple containing None as first element)? Commented Aug 29, 2018 at 6:20
  • Seems like None exists inside current_tact. Commented Aug 29, 2018 at 6:22
  • 3
    Try print(current_tact) and you'll immediately see the problem. Commented Aug 29, 2018 at 6:27
  • @hiroprotagonist, absolutely right. Output is:(None,) Thanks for guiding me in the right direction Aran-Fey, very basic mistake from my end. Commented Aug 29, 2018 at 6:29

1 Answer 1

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 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.