Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot import a class

Tags:

python

pygame

It's a game I'm making. Don't see the problems myself though.

Here's the error and the two .py files:

C:\Users\Rickard\My Programs\Python\slutarbete\New try>main.py
Traceback (most recent call last):
  File "C:\Users\Rickard\My Programs\Python\slutarbete\New try\main.py", line 6,
 in <module>
    from rabbits import Rabbit
  File "C:\Users\Rickard\My Programs\Python\slutarbete\New try\rabbits.py", line
 3, in <module>
    import main
  File "C:\Users\Rickard\My Programs\Python\slutarbete\New try\main.py", line 6,
 in <module>
    from rabbits import Rabbit
ImportError: cannot import name Rabbit

main.py

# -*- coding: utf-8 -*-

import pygame, sys, random, math
from rabbits import Rabbit
from pigs import Pig
from boars import Boar
from pygame.locals import *
from threading import Timer

pygame.init()
pygame.mixer.init()
mainClock = pygame.time.Clock()

WINDOW_WIDTH = 640
WINDOW_HEIGHT = 400

level = 1
while True:

...

And the rabbits.py file:

# -*- coding: utf-8 -*-
import pygame, sys, random, math
import main

class Rabbit(object):

    rabbitCounter = 0
    NEW_RABBIT = 40
    RABBIT_SIZE = 64

    ...

I sure can use some help with other obvious errors in this code.

like image 435
alsetalokin Avatar asked Feb 07 '26 14:02

alsetalokin


1 Answers

You have a circular import. In your main module you try to import from rabbits. But from rabbits you import main. But main is not finished importing yet so that results in an ImportError when you try to import anything from the rabbits module.

I don't know why you have that import there, but you should restructure your modules so that rabbits does not require anything from main.

See also Circular (or cyclic) imports in Python

Also for any Python project consisting of more than one module you should make that into a package instead.

like image 174
Iguananaut Avatar answered Feb 09 '26 07:02

Iguananaut