0

When I try to unpack a list data for a MySQL database query that has some columns with value 0, I get an error.

Name (varchar) Apples(int) Candies(int) Color (varchar)
John 5 0 Blue

If I unpack my query result like:

name, apples, candies, color = mylist

I'll get a NoneType error because candies values (in this example) is considered as None rather than 0.

The workaround I currently have is (which defeats the purpose and benefit of unpacking):

name = mylist[0]
if apples is None:
    apples = 0
else apples = mylist[1]
if candies is None:
    candies = 0
else candies = mylist[2]
color = mylist[3]

So my question is, is there anyway I can unpack mylist when one (or more) items have a value of 0 (and not null or None) without going through each one of them as "if x is None: x = 0"?

petezurich
  • 9,280
  • 9
  • 43
  • 57
pandasw
  • 3
  • 2
  • 1
    Why is 0 being turned into None? Nothing in MySQL does that automatically. You should figure out why that's happening and fix it. – Barmar Nov 19 '22 at 05:13
  • 1
    Your workaround doesn't make sense. Shouldn't it be `if myList[1] is None:`? – Barmar Nov 19 '22 at 05:14
  • Are you sure the table has `0` in the column? The SQL value that gets turned into `None` is `NULL`. – Barmar Nov 19 '22 at 05:15
  • Why does `None` prevent unpacking? – Barmar Nov 19 '22 at 05:16
  • "Shouldn't it be if myList[1] is None:" Yes, sorry lack of sleep.... if in this example the value of candies was 1 or any other integer, the unpacking would work fine, but whenever there's a 0 I get an error. – pandasw Nov 19 '22 at 05:20

1 Answers1

1

You can still using unpacking, just fix up the None values afterward.

name, apples, candies, color = mylist
if apples is None:
    apples = 0
if candies is None:
    candies = 0

If you have lots of columns to fix, you can use a list comprehension to fix up all the None values in the list.

mylist = [0 if x is None else x for x in mylist]
name, apples, candies, color = mylist

I doubt that 0 is really being turned into None, you probably have NULL values in the table. You can use IFNULL() to convert them:

SELECT name, IFNULL(apples, 0), IFNULL(candies, 0), color
FROM tablename
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Yes, I think the list comprehension may do the trick, I'm just wondering why this error happens in the first place. Any idea as to what may be the cause? The value are indeed keyed in and set as default as 0 and not NULL, and yet I have to treat them as NoneType. Anyway, your list comprehension is definitely a better way to go at it. Thank you for your help! – pandasw Nov 19 '22 at 05:27
  • You never actually showed the error traceback. Please post a [mre] – Barmar Nov 19 '22 at 05:29