Sign in to follow this  

Python imports and circular references

This topic is 4303 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm new to working with Python, and I'm a bit confused about the import statement. I'm trying to make a simple Tank shooter game. I have a class TankGame which contains the main method for launching the program, as well as some important program-wide variables such as the display surface, the window size, and the list of all the Tanks and Missiles in the game. I have another file which holds the Tank and Missile classes. Both hold position and velocity information, and Tank has a few other methods. The one I'm interested in is my Shoot() method. When I call Shoot(), I want to create a new Missile object in proximity to the Tank object and register the new Missile object with the TankGame method. TankGame is in a seperate file, so I would have to say "import tankgame" or "from tankgame import TankGame", correct? But when I do this, it gives me an error ImportError: cannot import name Tank My best guess is this is because I have a circular reference. Can anyone help me find a way to resolve this problem? Thanks.

Share this post


Link to post
Share on other sites
Could you post the relevant code (you can leave the classes empty), indicating, at the very least, how you import and refer to the various names in each module ?

Share this post


Link to post
Share on other sites
tank.py
import sys, math, pygame, vector, sprite
from vector import Vector
from sprite import Sprite
#from tankgame import *

class Tank:

[...]

def Shoot(self):
if self.cooldown == 0:
self.cooldown += 10
newmissile = Missile(self)
TankGame.Get().RegisterMissile(newmissile)

class Missile:
[...]


tankgame.py
import sys, pygame, time, tankcontroller, tank

from pygame.locals import *
from tank import *

class TankGame:
singleton = None
quitting = False

[...]

def Get():
return singleton

def RegisterMissile(self, missile):
self.missileList.append(missile)

[...]

game = TankGame()
game.Run()


These are the two files giving me trouble. If I leave out either of the import's refering to the other file, it breaks my code. If I include both imports. It breaks my code.

Share this post


Link to post
Share on other sites

This topic is 4303 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this