Cyclic dependencies like these, where the module player.py
imports the module enemy.py
and vice versa are indeed rather tricky in Python. But there are (at least) two ways to work around those:
First, you do not need to import a module to use classes from that module. Even without importing the enemy.py
module, you can use an instance of the Enemy
class, e.g. after it has been passed to the handle_collision
method as a parameter by some other module. Then, you could work around your problem by checking e.g. for other_object.__class__.__name__ == 'Enemy'
.
This works, but it is not very nice, and will cause problems with, e.g., subclasses of Enemy
.
Second, you do not have to put each class in it's own module/file, as it is common in, e.g., Java. In Python, it is perfectly normal and good practice to put many related classes in one and the same module. (One of the reasons why cyclic dependencies between modules are discouraged in Python is because needing them is considered a sign of bad system design.)
So my advice would be to put all of your "entity" classes into the same module, e.g. entities.py
class Entity:
def handle_collision(self, other_object):
pass
class Player(Entity):
def handle_collision(self, other_object):
if isinstance(other_object, Enemy):
# do stuff
class Enemy(Entity):
def handle_collision(self, other_object):
if isinstance(other_object, Player):
# do other stuff
Note that circular imports are in fact possible in Python, but should be used with care. For more about this, you can take a look at these two related posts.