Calling a Python File from another file and viceversa - python-3.x

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'

Related

Multiple bases have instance lay-out conflict in Robot Framework

I'm creating a new testing frameworks, I started to implement my own functions in *.py files, but when I try to run test, I've got following stack:
(venv) PLAMWS0024:OAT user$ robot -v CONFIG_FILE:"/variables-config.robot" ./catalog/tests/test1.robot
Traceback (most recent call last):
File "/Users/user/PycharmProjects/OAT/venv/bin/robot", line 5, in <module>
from robot.run import run_cli
File "/Users/user/PycharmProjects/OAT/venv/lib/python3.8/site-packages/robot/__init__.py", line 44, in <module>
from robot.rebot import rebot, rebot_cli
File "/Users/user/PycharmProjects/OAT/venv/lib/python3.8/site-packages/robot/rebot.py", line 45, in <module>
from robot.run import RobotFramework
File "/Users/user/PycharmProjects/OAT/venv/lib/python3.8/site-packages/robot/run.py", line 44, in <module>
from robot.running.builder import TestSuiteBuilder
File "/Users/user/PycharmProjects/OAT/venv/lib/python3.8/site-packages/robot/running/__init__.py", line 98, in <module>
from .builder import TestSuiteBuilder, ResourceFileBuilder
File "/Users/user/PycharmProjects/OAT/venv/lib/python3.8/site-packages/robot/running/builder/__init__.py", line 16, in <module>
from .builders import TestSuiteBuilder, ResourceFileBuilder
File "/Users/user/PycharmProjects/OAT/venv/lib/python3.8/site-packages/robot/running/builder/builders.py", line 20, in <module>
from robot.parsing import SuiteStructureBuilder, SuiteStructureVisitor
File "/Users/user/PycharmProjects/OAT/venv/lib/python3.8/site-packages/robot/parsing/__init__.py", line 380, in <module>
from .model import ModelTransformer, ModelVisitor
File "/Users/user/PycharmProjects/OAT/venv/lib/python3.8/site-packages/robot/parsing/model/__init__.py", line 18, in <module>
from .statements import Statement
File "/Users/user/PycharmProjects/OAT/venv/lib/python3.8/site-packages/robot/parsing/model/statements.py", line 453, in <module>
class Error(Statement, Exception):
TypeError: multiple bases have instance lay-out conflict
I suspect it's because in one of my files I'm trying to get variables from Robot Framework built in functionalities.
and I'm thinking it's because I'm trying to use protected methods, but I am not sure.
I found issue TypeError: multiple bases have instance lay-out conflict and it shows that there might be a mismatch in naming convention (or am I wrong?), but my project is a bit small, so the only option is that Robot can't see the function itself.
What can I miss?
Some code:
Test itself:
*** Settings ***
Documentation TO BE CHANGED
... SET IT TO CORRECT DESCRIPTION
Library ${EXECDIR}/file.py
Library String
*** Test Cases ***
User can do stuff
foo bar
from datetime import datetime
from robot.api import logger
from robot.libraries.BuiltIn import _Variables
from robot.parsing.model.statements import Error
import json
import datetime
from catalog.resources.utils.clipboardContext import get_value_from_clipboard
Vars = _Variables()
def foo_bar(params):
# Get all variables
country = get_value_from_clipboard('${COUNTRY}')
address = get_value_from_clipboard('${ADDRESS}')
city = get_value_from_clipboard('${CITY}')
postcode = get_value_from_clipboard('${POSTALCODE}')
And calling Vars:
from robot.libraries.BuiltIn import _Variables
from robot.parsing.model.statements import Error
Vars = _Variables()
def get_value_from_clipboard(name):
"""
Returns value saved inside variables passed in Robot Framework
:param name: name of the variable, needs to have ${} part
as example: ${var} passed in config file
:return: value itself, passed as string
"""
try:
return Vars.get_variable_value(name)
except Error as e:
raise Error('Missing parameter in the clipboard, stack:' + str(e))
What fixed issue:
uninstall all requirements from requirements.txt file and install all one-by-one.
Additional steps I tried:
comment out all files one-by-one and run only robot command - failed, got same errors
cleaned vnenv as described here: How to reset virtualenv and pip? (failed)
check out if any variable has same naming as described in python3.8/site-packages/robot/parsing/model/statements.py - none
So looks like there was some clash in installing requirements by PyCharm IDE

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

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

surprise.dataset is not a package

When I try to execute this code
import surprise.dataset
file = 'ml-100k/u.data'
col = 'user item rating timestamp'
reader = surprise.dataset.Reader(line_format = col, sep = '\t')
data = surprise.dataset.Dataset.load_from_file(file, reader = reader)
data.split(n_folds = 5)
I get this error:
Traceback (most recent call last):
File "/home/user/PycharmProjects/prueba2/surprise.py", line 1, in <module>
import surprise.dataset
File "/home/user/PycharmProjects/prueba2/surprise.py", line 1, in <module>
import surprise.dataset
ModuleNotFoundError: No module named 'surprise.dataset'; 'surprise' is not a package
But surprise is installed. How can I use it?
If you want to import a submodule, instead of doing:
import surprise.dataset
do:
from surprise import dataset
then in the rest of the code, reference it as dataset instead of surprise.dataset (i.e. replace surprise.dataset.Reader with dataset.Reader). If you don’t want to update the rest of your code, you can also just import the whole surprise module instead with:
import surprise

Access Class written in one python file From Another python file

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

Resources