user8497193
user8497193

Reputation:

Search in the list

class CommandManager:
        def __init__(self):
            self.commands = []

        def add_command(self, command: Command):
            if command is None:
                return None

            for target in self.commands:
                if target.name is command.name:
                    return None

            print(command.name, command.description, command.usage, command.min_arguments)  # debug

            self.commands.append(command)
            return command

        def get_command(self, name):
            if name is None:
                return None    
            for target in self.commands:
                if name is target.name:
                    return target    
            return None

What's wrong with this code? Adding to the array and looking for it in the add_command method works fine, but inget_command it does not find it. No value is None.

Upvotes: 1

Views: 75

Answers (2)

Fady Saad
Fady Saad

Reputation: 1189

is tests for identity, not equality. That means Python simply compares the memory address a object resides in.

you should use == operator to test equality of a string like:

if name == target.name:

Upvotes: 2

Danil Speransky
Danil Speransky

Reputation: 30453

is operator tests if two variables point to the same object. Use == instead.

if name == target.name:

Upvotes: 0

Related Questions