So I was deep in a refactoring session yesterday, working on a data validation function in Python. The code was supposed to take a list of mixed types, filter out non-integers, and return the sum. My initial pass had a subtle bug, and I didn't even notice it until Tabnine's suggestion stopped me in my tracks.
Here's what I had:
```python
def sum_valid_integers(data_list):
total = 0
for item in data_list:
if isinstance(item, int):
total += item
else:
# Log and skip non-integer values
print(f"Skipping non-integer: {item}")
return total
```
The logic seemed fine, right? It loops, checks the type, and adds. But Tabnine, after I typed `return total`, autocompleted a comment line that read `# Consider handling boolean values, as isinstance(True, int) returns True.` 🤯
Mind. Blown. I had completely forgotten that in Python, `bool` is a subclass of `int`. So `True` would be added as `1` and `False` as `0`, which was absolutely *not* the intent for my "integer sum" function. That's a sneaky bug waiting to happen!
I immediately fixed it using the suggestion:
```python
def sum_valid_integers(data_list):
total = 0
for item in data_list:
# Check for exact int type, not subclass
if type(item) is int:
total += item
else:
print(f"Skipping non-integer: {item}")
return total
```
This was more than just a line completionβit felt like a real-time code review. It caught a language-specific pitfall that's easy to miss.
Has anyone else had a moment where Tabnine's suggestion wasn't just convenient, but actually pointed out a non-obvious logic error or best practice? I'm starting to think its training on quality open-source code makes it surprisingly good at these nuanced corrections.
Happy coding!
Clean code, happy life
Good catch by the tool. That's a classic Python gotcha.
Your fix should use `type(item) is int` or check `isinstance(item, int) and not isinstance(item, bool)`. The second is more verbose, but correct if you're dealing with other int subclasses (though those are rare).
This is exactly why I never trust `isinstance` with primitives for validation. Use a direct type check or a custom predicate.
slow pipelines make me cranky