too-complex / R1260ΒΆ
Message emitted:
%s is too complex. The McCabe rating is %d
Description:
Used when a method or function is too complex based on McCabe Complexity Cyclomatic
Problematic code:
def fifty_percent_off(whole):
return (float(whole)) * 50 / 100
def calculate_sum_and_display_price_of_fruits(*fruits): # [too-complex]
# McCabe rating is 13 here (by default 10)
shopping_list = []
if "apple" in fruits:
v = fifty_percent_off(1.1)
shopping_list.append(v)
if "pear" in fruits:
shopping_list.append(0.8)
if "banana" in fruits:
shopping_list.append(1.2)
if "mango" in fruits:
shopping_list.append(3.5)
if "peach" in fruits:
shopping_list.append(0.5)
if "melon" in fruits:
shopping_list.append(4.9)
if "orange" in fruits:
shopping_list.append(2.0)
if "strawberry" in fruits:
shopping_list.append(2.5)
if "mandarin" in fruits:
shopping_list.append(2.3)
if "plum" in fruits:
shopping_list.append(0.5)
if "watermelon" in fruits:
v = fifty_percent_off(6.4)
shopping_list.append(v)
combine = zip(fruits, shopping_list)
for i in combine:
print(f"{i[0]} ${i[1]:.2f}")
total = sum(shopping_list)
print(f"Total price is ${total:.2f}")
fruits_to_buy = ["apple", "orange", "watermelon"]
calculate_sum_and_display_price_of_fruits(*fruits_to_buy)
Correct code:
FRUIT_PRICES = {
"apple": 1.1,
"pear": 0.8,
"banana": 1.2,
"mango": 3.5,
"peach": 0.5,
"melon": 4.9,
"orange": 2.0,
"strawberry": 2.5,
"mandarin": 2.3,
"plum": 0.5,
"watermelon": 6.4,
}
DISCOUNTED_FRUITS = ["apple", "watermelon"]
def fifty_percent_off(whole):
return (float(whole)) * 50 / 100
def get_price(fruit):
full_price = FRUIT_PRICES.get(fruit)
if fruit in DISCOUNTED_FRUITS:
return fifty_percent_off(full_price)
else:
return full_price
def display_fruit_and_price(fruits):
for fruit in fruits:
print(f"{fruit} ${get_price(fruit) :.2f}")
def get_total(fruits):
return sum(get_price(f) for f in fruits)
fruits_to_buy = ["apple", "orange", "watermelon"]
display_fruit_and_price(fruits_to_buy)
print(f"Total price is ${get_total(fruits_to_buy):.2f}")
Configuration file:
[main]
load-plugins=pylint.extensions.mccabe
Note
This message is emitted by the optional 'design'
checker, which requires the pylint.extensions.mccabe
plugin to be loaded.
Created by the design checker.