quantifiedcode / python-anti-patterns

An open collection of Python anti-patterns and worst practices.
https://quantifiedcode.github.io/python-anti-patterns
Other
1.71k stars 249 forks source link

built-in overriden in "correctness -> else clause on loop without a break statement" #100

Open CastixGitHub opened 7 years ago

CastixGitHub commented 7 years ago

The list built-in is overridden Thanks for your beautiful work :)

BrunoDesthuilliers commented 6 years ago

in https://docs.quantifiedcode.com/python-anti-patterns/correctness/else_clause_on_loop_without_a_break_statement.html :

def contains_magic_number(list, magic_number):
    for i in list:

:-)

CastixGitHub commented 6 years ago

Talking about correctness, instead of break, I think return is more appropriate here

>>> def contains_magic_number(numbers, magic_number):
...     for n in numbers:
...             if magic_number == n:
...                     return True
...     else:
...             return False
... 
>>> print("This list contains the magic number."
...       if contains_magic_number(range(10), 5)
...       else "This list does NOT contain the magic number.")
This list contains the magic number

otherwise do not use a loop at all, use a list comprehension or filter() instead

>>> def contains_magic_number(numbers, magic_number):
...     if len([n for n in numbers if n == magic_number]) != 0:
...             print("This list contains the magic number.")
...     else:
...             print("This list does NOT contain the magic number.")
... 
>>> contains_magic_number(range(10), 5)
This list contains the magic number.
Stigjb commented 5 years ago

This seems to have been fixed in https://github.com/quantifiedcode/python-anti-patterns/commit/5f6e7bf7eff4b3516450e455fdf1c62447a3ea76, so the issue should probably be closed.

However, the website still shows the old version that redefines list.