Access Class written in one python file From Another python file - python-3.x

I have 3 python file in same directory.
b.py
class Something_b():
def b(self):
print("hello from b")
c.py
class Something_c():
def c(self):
print("hello from c")
a.py
from .b import *
from .c import *
Something_b.b()
Something_c.c()
but i am getting some errors like
Traceback (most recent call last):
File "F:/testing/test1/a.py", line 1, in <module>
from .b import *
ModuleNotFoundError: No module named '__main__.b'; '__main__' is not a package

it's fairly simple, just import the class from the file (you're importing all but you shouldn't put a period before the filename. The period before the filename is what's causing the error.)
in file b:
class hello:
def h(self):
print("Hello")
Then in file a:
from b import hello
hello.h('')
As you can see it printed hello, you can have as many files it doesn't really matter, when I'm doing a larger project I'll have a file for every key part of it. It makes it easier to read/find the function you are looking to edit.

try this:-
a.py
from b import *
from c import *
x = Something_b()
x.b()
y = Something_c()
y.c()
Note:- First receipt class constructor then call belonging methods from class

Related

Calling a Python File from another file and viceversa

I have few common functions written in file a.py which is called from file b.py. And, also I have few common functions written in file b.py which is called from file a.py. but when I try to run these files I get error as unable to import name. Below is the code for reference.
I have just provided an example below, these files have common piece of code in real scenario which is specific to a functionality and that is the reason its being called from one another
a.py code below
from b import get_partner_id
def get_customer_id(tenant_id):
customer_id = tenant_id + "tenant_name"
return customer_id
def get_partner_details():
partnerid = get_partner_id()
data = {"partnerId": partnerid}
print(data)
b.py code below
from a import get_customer_id
def get_partner_id():
customer_id = get_customer_id("7687")
env = 'sandbox-all' + customer_id
return env
get_partner_id()
Below is the error for reference,
Traceback (most recent call last):
File "C:/testCases/b.py", line 1, in <module>
from a import get_customer_id
File "C:\testCases\a.py", line 2, in <module>
from b import get_partner_id
File "C:\testCases\b.py", line 1, in <module>
from a import get_customer_id
ImportError: cannot import name 'get_customer_id'

"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

Cyclic import in Python3

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

how to import function from sub directory in Python3

I have a project with below structure:
TestDir.init.py contains:
from . import TestSubDirFile
TestDir.TestSubDirFile.py contains:
class TestSubDirFile:
def test_funct(self):
print("Hello World")
ds_scheduler.py contains:
from TestDir import TestSubDirFile as tp
def test_job():
testobj = tp.test_funct()
print("Test job executed.")
if __name__ == "__main__":
test_job()
Getting Output as:
Traceback (most recent call last):
File "C:/Python_Projects/Test/com/xyz/ds/ds_schedular.py", line 9, in <module>
test_job()
File "C:/Python_Projects/Test/com/xyz/ds/ds_schedular.py", line 5, in test_job
testobj = tp.test_funct()
AttributeError: module 'TestDir.TestSubDirFile' has no attribute 'test_funct'
As per your directory structure
ds_scheduler.py
TestDir -- Directory Name
- TestSubDirFile.py - Python filename
Within TestSubDirFile.py file you have defined your class with name TestSubDirFile.
from TestDir import TestSubDirFile as tp
As per your above import statement you are only accessing till the py file.
To access test_func() method within class you need to follow below steps.
tsdf = tp.TestSubDirFile()
tsdf.test_funct()
Hope this helps

calling a tcl proc in python3

I am trying to call a tcl proc in a python program.
The tcl script starts with
proc scale_wigner-seitz_radii { } {
(I am not sure if I can put the full proc here, as this is a part of a licensed program).
This program is called by my python script:
#!/usr/bin/python3
import sys
from numpy import arange
from tempfile import mkstemp
from shutil import move, copy
from os import remove, close, mkdir, path
import Tkinter
def repll(file_path, pattern, subst):
print(pattern)
print(subst)
print(file_path)
r = Tkinter.Tk
# fullpath = str(subst) + "/" + file_path
fh, abs_path = mkstemp()
with open(abs_path, "w") as new_file:
with open(file_path, "r") as old_file:
for line in old_file:
new_file.write(line.replace(pattern.strip(),
str(subst).strip()))
r.tk.eval('source /home/rudra/WORK/xband/create_system_util.tcl')
r.tk.eval('proc scale_wigner-seitz_radii')
copy(abs_path, path.join(str(subst), file_path))
inpf = str(sys.argv[1])
a = []
print (inpf)
with open(inpf, "r") as ifile:
for line in ifile:
if line.startswith("lattice parameter A"):
a = next(ifile, "")
print(a)
for i in arange(float(a)-.10, float(a)+.10, 0.02):
if not path.exists(str(i)):
mkdir(str(i))
repll(inpf, a, i)
I havn't make a minimal example, because this seems better than explaining in english.
At the very end of def repll, it is calling the tcl proc. I have never encountered a tcl script before, and found the calling process from this question.
But when I am running this, I am getting error:
Traceback (most recent call last):
File "xband.py", line 41, in <module>
repll(inpf, a, i)
File "xband.py", line 24, in repll
r.tk.eval('source /home/rudra/WORK/xband/create_system_util.tcl')
AttributeError: class Tk has no attribute 'tk'
How I can solve this?
After Donal's Comment Thanks for your reply. After following your suggestion, I got same error from source line.
Traceback (most recent call last):
File "xband.py", line 41, in <module>
repll(inpf, a, i)
File "xband.py", line 24, in repll
r.tk.eval('/home/rudra/WORK/xband/create_system_util.tcl')
AttributeError: class Tk has no attribute 'tk'
Sorry if its silly, but since the tcl is in different file, I must source that first, right? And, as I said, this is the first tcl code I am looking at, please be elaborate.
The problem seems to be this line:
r = Tkinter.Tk
My guess is, you think this is creating an instance of Tk, but you're merely saving a reference to the class rather than creating an instance of the class. When you instantiate it, the object that gets returned has an attribute named tk, which the object internally uses to reference the tcl interpreter. Since you aren't instantiating it, r (which points to Tk) has no such attribute.
To fix it, instantiate the class by adding parenthesis:
r = Tkinter.Tk()
r will now be a proper reference to a Tk object, and should have a tk attribute, and with that you can call eval on raw tcl code.

Resources