duplicate-code / R0801ΒΆ

Message emitted:

Similar lines in %s files %s

Description:

Indicates that a set of similar lines has been detected among multiple file. This usually means that the code should be refactored to avoid this duplication.

Problematic code:

__init__.py:


apple.py:

class Apple:
    def __init__(self):
        self.remaining_bites = 3

    def take_bite(self):
        if self.remaining_bites > 0:
            print("You take a bite of the apple.")
            self.remaining_bites -= 1
        else:
            print("The apple is already eaten up!")

    def eaten_by_animal(self, animal):
        self.remaining_bites = 0
        print("The apple has been eaten by an animal.")

orange.py:

class Orange:  # [duplicate-code]
    def __init__(self):
        self.remaining_bites = 3

    def take_bite(self):
        if self.remaining_bites > 0:
            print("You take a bite of the apple.")
            self.remaining_bites -= 1
        else:
            print("The orange is already eaten up!")

    def eaten_by_animal(self, animal):
        if animal == "cat":
            raise ValueError("A cat would never do that !")
        self.remaining_bites = 0
        print("The orange has been eaten by an animal.")

Correct code:

__init__.py:


apple.py:

from fruit import Fruit


class Apple(Fruit): ...

fruit.py:

class Fruit:
    def __init__(self):
        self.remaining_bites = 3

    def take_bite(self):
        if self.remaining_bites > 0:
            print(f"You take a bite of the {self.__class__.__name__.lower()}.")
            self.remaining_bites -= 1
        else:
            print(f"The {self.__class__.__name__.lower()} is already eaten up!")

    def eaten_by_animal(self, animal):
        self.remaining_bites = 0
        print(f"The {self.__class__.__name__.lower()} has been eaten by an animal.")

orange.py:

from fruit import Fruit


class Orange(Fruit):
    def eaten_by_animal(self, animal):
        if animal == "cat":
            raise ValueError("A cat would never do that !")
        super().eaten_by_animal(animal)

Additional details:

If you need to make a change to the logic or functionality of the duplicated code, you will need to identify all the places that need to be changed, which can be time-consuming and error-prone. If there are multiple copies of the same code, then you will also need to test each copy to ensure that the functionality is correct. Duplicate code can be confusing for someone who is trying to understand the logic and flow of the code if they come across multiple identical or nearly identical blocks of code. The reader can then skim and think something is identical when it actually isn't. This is particularly true during review.

Created by the similarities checker.