You’re using Python which is sensitive to white-space, in order for the if statement to determine whether or not the attack method is called, it needs to be indented properly:
loop:
enemy = self.findNearestEnemy()
if enemy:
self.attack(enemy)
else:
self.moveXY(...)
Otherwise you have:
if enemy:
# do nothing
self.attack(enemy) #always try to attack the enemy variable.