List comprehension and appending None values

Hey there,

So this is my favorite mistake, unfortunately not mine this time, but whenever I’m conducting code review I’ll always make sure to look for it ( yeah, I’m in QC and I’m evil)

Here’s a simple example of what can go wrong:

 

myList = []

for i in range(3):
internalList = []
for j in range(3):
internalList.append(j)
myList.append(internalList)

print(myList)

So we somehow mustered up the courage to go for list comprehensions ( again, we’re headbanging and can’t really decide why we do what we do! )


>>myList1 = []
>>myList = []
>>myList1.append([myList.append([j for j in range(3)]) for i in range(3)]) >>print(myList1)
[[None, None, None]]
>>print(myList)
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]

Should’ve stopped with myList, eh?
So the last append is trying to append something thinking it’s a list or has a return value where’s there’s nothing. I’ve seen the same mistake in other scenarios as well, e.g. when doing regression testing the inputs cause the function to enter into branches which do not have a return value where’s they should.

Advertisements

A mistake with Python’s map function

This is just a short note on today’s mistake which caused me to go back and write about 7 unit tests just to find out where I’d made a mistake.
so, here’s a simplified version of my mistake:

upper_case_strings = map(lambda x: x.upper(), lower_case_strings)

see the problem? YUP, I needed to return a list whereas I’m just returning a map object.

upper_case_strings = list(map(lambda x: x.upper(), lower_case_strings))

I’ve noticed I do this sort of mistakes a lot. Thinking again, it might be a good idea for me, and all other metal-heads who are headbanging while coding, to go for TDD and also think about the return values while coding.