Home > Enterprise >  cannot import name "B" from "A"
cannot import name "B" from "A"

Time:04-18

I am here to ask what seems to be a very dumb question, but just cannot find a fix for it. I'm just a beginner and I've also searched StackOverflow for multiple results but such problems are not related to mine. If I've missed one, I'm sorry about that.

my problem is that I'm trying to re-create one of my first console games into an OOP one, but for some reason, I cannot import modules?

firs, I would like to say that I created this on my laptop with Pop os. and that the mentioned two file are the only file on the directory.

so I created a battle_main.py and battle_mechanics.py

on the battle_mechanics.py, it only has the following lines:

class User_Interface:
    def __init__(self):
        self.player_health = 30
        self.squid_health = 30

and on the battle_main.py:

from battle_mechanics import User_Interface

ui = User_Interface()

it's literally just that, yet I cannot import it. it's resulting in ImportError: cannot import name 'User_Interface' from 'battle_mechanics' I know that it's a very simple problem, but I really can't find any fix to it? in fact, I think there's not even a problem in the way I'm importing it. it just wont work. any help is appreciated.

CodePudding user response:

I'm not sure as to why the method your trying isn't working. To the best of my knowledge what your doing already is correct. However one alternative workaround is to put battle_mechanics.py inside a folder package. Include __init__.py inside that folder with the following code:

from .battle_mechanics import *

Then when you use battle_main.py you can use the following import statement.

from package import User_Interface

This should sort out your issue.

  • Related