• Advertisement
Sign in to follow this  

[Python] 'module' object has no attribute '...'

This topic is 3725 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

Hey! I have the following problem:
Traceback (most recent call last):
  File "C:\Oskar\Python\magic_game\main.py", line 3, in <module>
    import magic_game.game_state as game_state
  File "C:\oskar\Python\magic_game\game_state.py", line 7, in <module>
    import magic_game.graphics as graphics
  File "C:\oskar\Python\magic_game\graphics.py", line 5, in <module>
    import magic_game.camera as camera
  File "C:\oskar\Python\magic_game\camera.py", line 2, in <module>
    import magic_game.singletons as singletons
  File "C:\oskar\Python\magic_game\singletons.py", line 1, in <module>
    import magic_game.game_state as game_state
AttributeError: 'module' object has no attribute 'game_state'
I've tried google but that didn't help me much. Everything I found seemed to be about 3rd party libraries. I'm using PyGame by the way, if that can have anything to do with it. magic_game is a package. The others are ordinary modules. It all started when I started using packages. Didn't have a problem before.

Share this post

Link to post
Share on other sites
We need to know more about magic_game. Is it a single file module, or is it a directory? If the former, does it have an __init__() function? If the latter, does it have an __init__.py file? What are these attributes supposed to be? How are they defined?

Post the code, if you can.

Share this post

Link to post
Share on other sites
magic_game is a package/directory. It has an __init__.py file, which is empty. The others are modules.

I don't know how much you need to see, but let's start with this...
By the way, none of the modules has an __init__() function (the classes have though :P).


import pygame

import magic_game.client as client
import magic_game.server.server as server

def main():
msg = raw_input('Server (s) or client (c)?')
if msg == 's':
s = server.Server()




import time
from collections import deque

import pygame
from pygame.locals import *

import magic_game.graphics as graphics
import magic_game.consts as consts
import magic_game.singletons as singletons
import magic_game.orders as orders
from magic_game.tools.create_map import create_map

class GameState(object):
def __init__(self):
self._player_id = None

self._sprite_map, self._terrain_map, self._obstacle_map = create_map()

self._map_size = len(self._sprite_map), len(self._sprite_map[0])

self._unit_list = []

self._moving_unit = None

#The move queue is for coping with lag, nothing else.
#If the client gets a network msg telling a unit to move, and
#the previous unit is not yet finished, then the order gets placed
#in the queue. (Use append and popleft)
self._move_queue = deque()

self._last_tick = pygame.time.get_ticks()

def set_player_id(self, id):
"""Used in the beginning to give the client a player id"""
if self._player_id == None:
self._player_id = id
raise Exception("Player ID already set")

def update(self):
"""Called each frame to update the game state"""
if self._moving_unit:
current_tick = pygame.time.get_ticks()

if current_tick - self._last_tick > consts.TICK_MS:

if not self._moving_unit.order:
self._moving_unit = None

self._last_tick = current_tick
if self._move_queue:
self._moving_unit = self._move_queue.popleft()
self._last_tick = pygame.time.get_ticks()

if self._player_id == 0:

def start_turn(self):
"""Call this each time a turn starts"""

def end_turn(self):
"""Call this each time a turn ends"""

def draw_map(self):
"""Draws the terrain"""
print singletons.Graphics
for x in xrange(singletons.Camera.position[0] / consts.TILE_SIZE,
(singletons.Camera.position[0] + consts.X_RES) / consts.TILE_SIZE + 1):
for y in xrange(singletons.Camera.position[1] / consts.TILE_SIZE,
(singletons.Camera.position[1] + consts.Y_RES) / consts.TILE_SIZE + 1):
if (0 <= x < self._map_size[0] and 0 <= y < self._map_size[1]):
pos = (x * consts.TILE_SIZE, y * consts.TILE_SIZE)
singletons.Graphics.draw_at_world_pos(self._sprite_map[x][y], pos)

def draw_units(self):
"""Draws the units"""
for unit in self._unit_list:

def want_to_move(self, unit, target):
"""If a unit wants to move (called by input state)
If a unit is already moving, the request is ignored,
otherwise send the event to event_handler"""

if not self._moving_unit:
singletons.EventHandler.send_move_unit(unit, target)

def give_unit_order(self, unit, order):
"""Gives an order to a unit, cannot be ignored"""
if self._moving_unit:
self._moving_unit = unit

def add_unit(self, unit):
"""Adds a new unit to the game"""
if self.obstacle(unit.position):
raise Exception("Cannot place a unit there")

def is_over(self):
#Should be handled elsewhere
for event in pygame.event.get():
if event.type == Quser_interfaceT:
return True
elif event.type == KEYDOWN and event.key == K_ESCAPE:
return True
return False


def a_unit_is_moving(self):
"""Returns true if a unit is currently moving"""
if self._moving_unit:
return True
return False

def get_unit_at(self, pos):
"""Return the unit at the specified square, or None
if there is no unit at the square."""

for unit in self._unit_list:
if unit.position == pos:
return unit
return None

def obstacle(self, pos):
return self._obstacle_map[pos[0]][pos[1]]

def _manage_creeps(self):
"""Manage the creeps when its their turn to move
Called only by player 0"""


def _set_obstacle(self, pos):
"""Sets obstacle map to True at the specified position."""
self._obstacle_map[pos[0]][pos[1]] = True

def _remove_obstacle(self, pos):
"""Sets obstacle map to False at the specified position."""
self._obstacle_map[pos[0]][pos[1]] = False

def _get_map_size(self):
return self._map_size

def _get_sprite_map(self):
return self._sprite_map

def _get_terrain_map(self):
return self._terrain_map

def _get_obstacle_map(self):
return self._obstacle_map

map_size = property(_get_map_size)

sprite_map = property(_get_sprite_map)
terrain_map = property(_get_terrain_map)
obstacle_map = property(_get_obstacle_map)


import pygame
from pygame.locals import *

import magic_game.consts as consts
import magic_game.camera as camera
import magic_game.singletons as singletons
from magic_game.tools.tuples import *

class Graphics(object):
def __init__(self):
self._screen = pygame.display.set_mode((consts.X_RES, consts.Y_RES))
self._sprite_map = {}


self._sprite_map = {
consts.GRASS : self._load_image('sprites\grass.png'),
consts.STONE : self._load_image('sprites\stone.png'),
consts.SAND : self._load_image('sprites\sand.png'),
consts.WARRIOR : self._load_image('sprites\warrior.bmp', 'auto'),
consts.HIGHLIGHT_OVER : self._load_image('sprites\highlighting_over.bmp', 'auto'),
consts.HIGHLIGHT_UNDER : self._load_image('sprites\highlighting_under.bmp', 'auto')

def draw_at_world_pos(self, sprite_number, position):
tuple_sub(position, singletons.Camera.position))

def draw_at_screen_pos(self, sprite_number, position):
self._screen.blit(self._sprite_map[sprite_number], position)

def _load_image(self, name, colorkey=None):
surface = pygame.image.load(name)
surface = surface.convert()
if colorkey is not None:
if colorkey is 'auto':
colorkey = surface.get_at((0,0))
surface.set_colorkey(colorkey, RLEACCEL)
return surface


import magic_game.consts as consts
import magic_game.singletons as singletons
import magic_game.game_state as game_state

class Camera(object):
def __init__(self):
self._position_x = 15
self._position_y = 15
self._mouse_scroll_speed = 4
self._keyboard_scroll_speed = 4

def move_to(self, pos):
self._position = pos

def scroll_up(self):
self._position_y -= self._mouse_scroll_speed

if self._position_y < 0:
self._position_y = 0

def scroll_down(self):
self._position_y += self._mouse_scroll_speed

if self._position_y + consts.Y_RES > singletons.GameState.map_size[1] * consts.TILE_SIZE:
self._position_y = singletons.GameState.map_size[1] * consts.TILE_SIZE - consts.Y_RES

def scroll_left(self):
self._position_x -= self._mouse_scroll_speed

if self._position_x < 0:
self._position_x = 0

def scroll_right(self):
self._position_x += self._mouse_scroll_speed

if self._position_x + consts.X_RES > singletons.GameState.map_size[0] * consts.TILE_SIZE:
self._position_x = singletons.GameState.map_size[0] * consts.TILE_SIZE - consts.X_RES

def _get_position(self):
return (self._position_x, self._position_y)

position = property(_get_position)


import magic_game.game_state as game_state
import magic_game.camera as camera
import magic_game.user_interface as user_interface
import magic_game.graphics as graphics
import magic_game.input_state as input_state
import magic_game.server_connection as server_connection
import magic_game.event_handler as event_handler

GameState = None
Camera = None
UserInterface = None
Graphics = None
InputState = None
ServerConnection = None
EventHandler = None

def initialize():

global Graphics
Graphics = graphics.Graphics()

global GameState
GameState = game_state.GameState()

global Camera
Camera = camera.Camera()

global UserInterface
UserInterface = user_interface.UserInterface()

global InputState
InputState = input_state.InputState()

global EventHandler
EventHandler = event_handler.EventHandler()

global ServerConnection
ServerConnection = server_connection.ServerConnection()

Share this post

Link to post
Share on other sites
I believe it may just be a typo; if you go down the line of errors you import game_state, but the class is name GameState.

Share this post

Link to post
Share on other sites
No that's not it, the module name is game_state.py, and if you look in the error message (Traceback) I execute the same line "import magic_game.game_state" before that.

It seems like a circular dependency, although I'm almost 100% sure it worked before. The only new thing is that I divided my files into packages (except for magic_game, the top-level package, there is units, orders, tools etc).

I tried with a little sample if a circular dependency caused a problem, and it did not in the little sample.

Share this post

Link to post
Share on other sites
The reason for your error is, as you said, a circular dependency. game_state imports singletons, which in turn imports game_state. As I recall, if you just use the full name when importing a module (ie. import magic_game.game_state instead of import magic_game.game_state as game_state) you won't receive the error.

However, I believe the bigger problem is your heavy use of singletons. They really don't seem warranted in your case. It would probably be better just to create an instance of each class in a function somewhere, and then pass them around as parameters. It helps avoid problems like these, and the numerous necessary imports.

If you do insist on using singletons, I feel a better way is to implement them as modules, rather than as classes. This enforces the 'can only have one instance' requirement.

Share this post

Link to post
Share on other sites
Ok, thank you very much!

Hm... singletons... I feel that passing around lots of parameters makes the code less readable. I've tried it in other projects.

Singletons as modules ey... hmm... maybe.

By the way I read that if I import within the same package, like from game_state.py I import event_handler.py like this: "import event_handler", the event_handler module gets put into sys.modules. But if I import it as: import magic_game.event_handler, then that's a new entry in sys.modules (magic_game.event_handler instead of just event_handler). So the modules load twice. Why is that? Is there some benefit of doing it that way? I don't see it!

EDIT: Hm, yeah I do, the two modules don't have to be the same... But couldn't Python check if it's within a package if one uses the short version...

By the way, I'm prolly gonna throw singletons out the window, and just instantiate the classes once in Client, my main class so to speak.

[Edited by - tufflax on January 10, 2008 12:45:10 PM]

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement