Cyclic import in Python3 - python-3.x

I have the following directory structure:
my-game/
__init__.py
logic/
__init__.py
game.py
player.py
game.py and player.py have import dependency on each other (cyclic imports).
game.py has the following definition.
from logic.player import RandomPlayer, InteractivePlayer
T = 8
class Game:
def __init__(self, p1, p2)
...
# some other things
if __name__ == '__main__':
p1 = RandomPlayer()
p2 = InteractivePlayer()
g = Game(p1, p2)
...
player.py is as follows:
from logic.game import T
class Player:
def __init__(self):
...
class RandomPlayer(Player):
def __init__(self):
...
class InteractivePlayer(Player):
def __init__(self):
...
I am trying to run the game from logic/ directory but I get the following error.
$ python3 game.py
Traceback (most recent call last):
File "game.py", line 2, in <module>
from logic.player import RandomPlayer, InteractivePlayer
ModuleNotFoundError: No module named 'logic'
I then tried running game.py from the directory higher up (my-game/).
$ python3 logic/game.py
Traceback (most recent call last):
File "logic/game.py", line 2, in <module>
from logic.player import RandomPlayer, InteractivePlayer
ModuleNotFoundError: No module named 'logic'
What am I doing wrong? How can I make these cyclic imports work?
I have also tried using this import in player.py
from .game import T
and using
from .player import RandomPlayer, InteractivePlayer
in game.py.
In this case, I get a different error. For example, when running from my-game/,
$ python3 logic/game.py
Traceback (most recent call last):
File "logic/game.py", line 2, in <module>
from .player import RandomPlayer, InteractivePlayer
ModuleNotFoundError: No module named '__main__.player'; '__main__' is not a package
I get a similar error when running from logic/ directory.
I looked at this post but didn't understand where I was going wrong.

You are made a circulair import in your code try to remove it from your import
Vist this link you can find some other info about circular import :Remove python circular import

Related

Why is my program throwing exception 'xyz' is not a package?

I have the following setup in my Spyder ide:
this program is showing the following exception:
runfile('C:/Users/pc/source/repos/python_package_and_module_test/main.py', wdir='C:/Users/pc/source/repos/python_package_and_module_test')
Reloaded modules: jupyter_client.session, zmq.eventloop, zmq.eventloop.ioloop, tornado.platform, tornado.platform.asyncio, tornado.gen, zmq.eventloop.zmqstream, jupyter_client.jsonutil, jupyter_client.adapter, spyder, spyder.pil_patch, PIL, PIL._version, PIL.Image, PIL.ImageMode, PIL.TiffTags, PIL._binary, PIL._util, PIL._imaging, cffi, cffi.api, cffi.lock, cffi.error, cffi.model
Traceback (most recent call last):
File "C:\Users\pc\source\repos\python_package_and_module_test\main.py", line 1, in <module>
import token.factoryclass as a
ModuleNotFoundError: No module named 'token.factoryclass'; 'token' is not a package
how can I resolve this issue?
source code:
my files are as follows:
.\
python_package_and_module_test.py
import token.factoryclass as a
var = a.factoryclass();
var.print();
factoryclass.py
class factoryclass(object):
def print(object):
print("factoryclass")
tokenclass.py
class tokenclass(object):
def print(object):
print("tokenclass")
factory\
factoryclass.py
class factoryclass(object):
def print(object):
print("factory.factoryclass")
tokenclass.py
class tokenclass(object):
def print(object):
print("factory.tokenclass")
token\
factoryclass.py
class factoryclass(object):
def print(object):
print("token.factoryclass")
tokenclass.py
class tokenclass(object):
def print(object):
print("token.tokenclass")
However, the same package and module structure is working in repl.it:

ModuleNotFoundError: No module named in PyCharm

I was able to run the project using the command line, but from last 1 day I am not able to run the command from the command line However using GUI the project is running fine...
C:\Users\tester\PycharmProjects\Selenium\SampleProjects\POMProjectDemo\Tests>py
thon login.py
Traceback (most recent call last):
File "login.py", line 6, in <module>
from SampleProjects.POMProjectDemo.Pages.loginPage import LoginPage
ModuleNotFoundError: No module named 'SampleProjects'
C:\Users\tester\PycharmProjects\Selenium\SampleProjects\POMProjectDemo\Tests>py
thon -m unittest login.py
E
======================================================================
ERROR: login (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: login
Traceback (most recent call last):
File "C:\Users\tester\AppData\Local\Programs\Python\Python37-32\lib\unittest\
loader.py", line 154, in loadTestsFromName
module = __import__(module_name)
File "C:\Users\tester\PycharmProjects\Selenium\SampleProjects\POMProjectDemo\
Tests\login.py", line 6, in <module>
from SampleProjects.POMProjectDemo.Pages.loginPage import LoginPage
ModuleNotFoundError: No module named 'SampleProjects'
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
[![Tests/login.py
import time
from selenium import webdriver
import unittest
from selenium.common.exceptions import NoSuchElementException
from SampleProjects.POMProjectDemo.Pages.loginPage import LoginPage
from SampleProjects.POMProjectDemo.Pages.homePage import HomePage
import HtmlTestRunner
from SampleProjects.POMProjectDemo.Utility.XLUtil import getData
class LoginTest(unittest.TestCase):
#classmethod
def setUpClass(cls):
cls.driver = webdriver.Chrome(executable_path='F:/Selenium/chromedriver.exe')
cls.driver.implicitly_wait(10)
cls.driver.maximize_window()
def test_login_valid(self):
path = 'c:/Users/mahmood/PycharmProjects/Selenium_automaton/Login.xlsx'
# global path
driver = self.driver
row = getData.getRowCount(path,'Sheet1')
for r in range(2,row+1):
driver.get("https://opensource-demo.orangehrmlive.com/")
userN = getData.readData(path,'Sheet1',r,1)
passW = getData.readData(path,'Sheet1',r,2)
Same code was running fine, what changes I have done not able to debug it.

"ModuleNotFoundError" when importing my own classes

I have 2 files, both are in the same folder.
The file that I am trying to import is "HelloWorldClass.py"
(Code to HelloWorldClass.py)
class HelloWorld():
def __init__(self):
print("Hello World")
and the file that I am calling "HelloWorldClass" from is "ClassTest.py"
(Code to ClassTest.py)
from Classes import HelloWorldClass
HelloWorld()
and for some reason, I am getting this error...
Traceback (most recent call last):
File "D:/Coding file/Owl Hoot/Classes/ClassTest.py", line 3, in <module>
from Classes import HelloWorldClass
ModuleNotFoundError: No module named 'Classes'
>>>
Both files are in the Classes file. I don't see what I am doing wrong, can anyone help?
If both are in the same directory you can import like that:
from HelloWorldClass import HelloWorld

ModuleNotFoundError: No module named X although the module does exist

I have a very strange error with Python.
python main1.py
Traceback (most recent call last):
File "main1.py", line 1, in <module>
from sfr import hello
File "C:\sfr\hello.py", line 1, in <module>
from constants1 import OBJECT_NAME
ModuleNotFoundError: No module named 'constants1'
My main1.py looks like this
from sfr import hello
print('Hello World')
type sfr\hello.py
from constants1 import OBJECT_NAME
type sfr\constants1.py
OBJECT_NAME = 'salesforce_object_name'
I am unable to fathom this why am i getting no module named constants1 ?
The constants1.py is located in sfr folder
Since you are running the main1.py file from the parent directory (outside sfr), the import path should be from the base. That is,
from sfr.constants1 import OBJECT_NAME
You probably need to give imports from the root path of your project. If sfr is a package at root level, your statement should be:
from sfr.constants1 import OBJECT_NAME

Python version related error

I am trying to generate an HTML test report by using Selenium webdriver library HTMLTestRunner. I am using Python 3.4 version and I have a version related error. Refer following snippet.
import unittest`enter code here`
import HTMLTestRunner
from selenium import webdriver
from selenium.webdriver.common.alert import Alert
from selenium.webdriver.common.keys import Keys
class GreenlamTest(unittest.TestCase):
#classmethod
def setUp(cls):
cls.driver=webdriver.Firefox()
cls.driver.implicitly_wait(30)
cls.driver.maximize_window()
cls.driver.get('https://www.google.co.in')
def test_checkTitle(self):
assert "Google" in self.driver.title
def test_searchtest(self):
driver = self.driver
elem = self.driver.find_element_by_name("q")
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
#classmethod
def tearDown(cls):
cls.driver.quit()
if __name__ == '__main__':
HTMLTestRunner.main
Output
Finding files... done.
Traceback (most recent call last):
File "C:\Users\vaibhav\Desktop\Selenium Softwares\eclipse-jee-luna-SR2-win32-x86_64\eclipse\plugins\org.python.pydev_4.0.0.201504132356\pysrc\pydev_runfiles.py", line 468, in __get_module_from_str
mod = __import__(modname)
File "C:\Users\vaibhav\Desktop\Selenium Softwares\Practice\pythondemo\Htmlreport.py", line 2, in <module>
import HTMLTestRunner
File "C:\Users\vaibhav\Desktop\Selenium Softwares\Practice\pythondemo\HTMLTestRunner.py", line 94, in <module>
import StringIO
ImportError: No module named 'StringIO'
ERROR: Module: Htmlreport could not be imported (file: C:\Users\vaibhav\Desktop\Selenium Softwares\Practice\pythondemo\Htmlreport.py).
Importing test modules ... done.
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
You are getting error because your folder name Selenium Softwares has a space in it where your Htmlreport is present. Replace the folder name to exclude space out of it, probably an underscore or camelCase, etc... like this Selenium_Softwares . Here's how -
file: C:\Users\vaibhav\Desktop\Selenium_Softwares\Practice\pythondemo\Htmlreport.py)
Hope this helps.

Resources