Import class into another folder in the same package python - python

I am trying to create a package for my own use and cannot seem to be able to import a class into another folder. Here is a image of my current directory.
I am trying to import a class from strategies.core into my test/test_symbol.py file but it keeps giving me an ModuleNotFoundError
Error
Traceback (most recent call last):
File "c:\Users\Francois\Desktop\H4Impulse\test\test_symbol.py", line 6, in <module>
from strategies.core import Symbol
ModuleNotFoundError: No module named 'strategies'
test_symbol.py
import unittest
# import sys
# sys.path.append(r"C:\Users\Francois\Desktop\H4Impulse")
from strategies.core import Symbol
# from ..strategies.core import Symbol <--- this also doesn't work
class TestSymbol(unittest.TestCase):
pass
unittest.main()
it works when I use sys.path.append to append the path but I feel like this shouldn't be necessary. Any help would be appreciated.

Problem lies in your path. You are using:
absolute path in sys.path.append
relative path in your import
Probably if you call sys.path.append(r"./") it would raise the same ModuleNotFoundError error.
Since you are running the script "c:\Users\Francois\Desktop\H4Impulse\test\test_symbol.py", your working directory is probably set as "c:\Users\Francois\Desktop\H4Impulse\test". In this folder, the module strategies does not exist.
Finally, you should either:
Set "c:\Users\Francois\Desktop\H4Impulse" as your working directory (suggested if it is THE directory of your project)
Use relative imports

Related

How to make the imports in python in a project of several modules organised in different folders?

I am building a software. I organised the different code in differents python files (the modules) organised in different folders.
It was working like a charm. Then today it doesn't work anymore as I have some issues:
ModuleNotFoundError: No module named 'modules.mymodulesteam'
This is how my code is organized:
MySoftware/
- start.py
- modules/
-- mymodules.py
-- prepare.py
-- mymodulesteam.py
In the start.py file, I have this import:
from modules import prepare_envir_appium
in prepare.py I have this line of import
import modules.mymodulesteam as mymodules
When I execute "start.py", I have this error message in the console:
Traceback (most recent call last):
File "E:\MySoftware\modules\prepare.py",
import modules.mymodulesteam as mymodules
ModuleNotFoundError: No module named 'modules.mymodulesteam'
so I search for help and I saw I had to add some _init.py file in my folder "modules". I did it and it didn't work. I get the exact same issue.
I read every single post regarding this kind of issue and tried much stuff.
from modules import mymodulesteam
from . import mymodulesteam
etc...
And I get this kind of errors:
Traceback (most recent call last):
File "E:\MySoftware\modules\prepare.py",
from modules import mymodulesteam as mymodules
ImportError: cannot import name 'mymodulesteam' from 'modules' (E:\MySoftware\modules\__init__.py)
So I removed this "_ init _.py" file and tested again. I get this error this time:
Traceback (most recent call last):
File "E:\MySoftware\modules\prepare.py",
from modules import mymodulesteam as mymodules
ImportError: cannot import name 'mymodulesteam' from 'modules' (unknown location)
It used to work very well. I don't know what happened. Does anyone can help me please?
It doesn’t work because the modules are not in the same path and the script doesn’t know where to look.
Your current start.py file looks like this,
from modules import prepare_envir_appium
Instead, do this at the top of your start.py file, because your prepare_envir_appium.py file is located in modules.
import sys
sys.path.insert(0,"../modules")
import prepare_envir_appium
Now you can access your functions using prepare_envir_appium.functionname.
You can also do this,
import sys
sys.path.insert(0,"../modules")
import prepare_envir_appium as per
Now you can access the functions using per.functionname within start.py.
You can also import specific functions like this,
import sys
sys.path.insert(0,"../modules")
from prepare_envir_appium import functionname1, functionname2
and you can just run them using their function names.
However, if you are looking at the prepare.py script, because the module is in the same folder as the script, all you have to do is import the file name like below without the .py extension.
You can follow the same import naming conventions as above.
import mymodulesteam
or
import mymodulesteam as mmt
or
from mymodulesteam import function1, function2

Cannot import modules from other folders

I am currently having an issue with importing files from other directories in my python project.
My current file structure is
Project
- Backend
- Config
+ __init__.py
+ databaseConfig.py
- DataAccess
+ __init__.py
+ sqlConns.py
- __init__.py
- api.py
- main.py
- setup.py
What I am trying to do is import /Config/databaseConfig.py file into /DataAccess/sqlConns.py file. I get the following error when trying to run the sqlConns.py file
PS C:\source\repos\aaStats\aaStats> py .\Backend\DataAccess\sqlConns.py
Traceback (most recent call last):
File "C:\source\repos\aaStats\aaStats\Backend\DataAccess\sqlConns.py", line 2, in <module>
import Config.databaseConfig
ModuleNotFoundError: No module named 'Config'
I have also tried using relative imports, but I am met with another error.
PS C:\source\repos\aaStats\aaStats> py .\Backend\DataAccess\sqlConns.py
Traceback (most recent call last):
File "C:\source\repos\aaStats\aaStats\Backend\DataAccess\sqlConns.py", line 2, in <module>
from ..Config import databaseConfig as dbcfg
ImportError: attempted relative import with no known parent package
Config/databaseConfig.py contains database configuration parameters that I want to reference is various places in my project. It isn't a huge deal if I had to move this single file in order to get it to be referenced properly, but I will want to use structures like this for files later on in my project.
Here are some details about my files:
/Config/__init__.py
from . import databaseConfig
/DataAccess/__init__.py
from . import sqlConns
Backend/__init__.py
from . import DataAccess
from . import Config
Backend/setup.py
from setuptools import setup, find_packages
setup(
name='aaStatsApi',
version='0.1.0',
packages= ['DataAccess','Config'],
install_requires=[
'fastapi==0.63.0',
'uvicorn==0.13.4',
'requests==2.25.1',
'pyodbc==4.0.30',
]
)
Check out this post.
The fact that you can't perform relative imports so easily is by design, for better or for worse. The ideal way is have your main script in the root (Backend) directory and do all your calls from there. The function that has __name__ == __main__ is your calling function. If you do not directly call Calls.py or Configs.py from a console, but are calling them from another main function within your root directory, you should be able to place the following into Conns.py:
# FILE: DataAcess\sqlConns.py
from Config.dataBaseConfig import * # or whatever you need to import
Again, the key is to ensure that your starting point in from your root project directory.
NOT RECOMMENDED:
For risk of getting downvoted, and I do not recommend this, but you could append the relative path to your calling class:
import sys, os
sys.path.append(os.path.abspath("../Config"))
from sqlConns import * # or whatever
sys.path.pop() # clear sys.path

Python Import file from sibling folder

I was trying to import a function from a sibling folder and i could, i look for documentation and didnt found something useful, can you help me please?
I have a folder named fold1, inside i have fold2 and fold3, inside fold2 i have filetoimport.py, it has:
def fntest(a, b):
return print(a+b)
And i want to import that function from inside fold3 file main.py, there i have
from fold2 import filetoimport
filetoimport.fntest(2,2)
Then i get an error:
Traceback (most recent call last):
File "fold3/main.py", line 1, in <module>
fold1 import filetoimport
ImportError: No module named 'fold1'
Hope you can help me :)
I also tried
from fold1.fold2 import filetoimport
But it failed.
Alright, this should work
import sys
import os
sys.path.insert(1,os.popen('pwd').read().replace('3\n','2'))
import filetoimport
filetoimport.fntest(2,2)
you just need to add the target folder to the python runtime path
You need to import the parent folder as a path the program can check inside for more modules. I had some luck with this
import os
import sys
sys.path.append(os.path.realpath('..'))
from fold2 import filetoimport
filetoimport.fntest(2,2)
As far as I have understood, your folder structure is as below
fold1
fold2
-- filetoimport.py
fold3
-- main.py
It seems that your are executing the main.py file from terminal (by opening fold1 path) as
python3 fold3/main.py
Instead you should execute the command as
python3 -m fold3.main
Since the argument is a module name, you must not give a file extension (.py)
On the other hand if you open fold1 as a project in IDE like pycharm or intellij idea and execute main.py via IDE itself, it wont give you an error.
Hope, this will solve your problem.

How do I import a Python module in the same root directory but in a different sub-directory?

I have a number of Python files in a parent folder called 'API' and I'm trying to link them together:
API/auth/module1.py
API/subfolder/prgm.py
From the parent to the child folders, I have an init.py file containing paths or program names to call, however when I go to execute '/subfolder/prgm.py' that has a call to import 'module1.py', I get the following error at execution:
machine01% ./prgm.py
Traceback (most recent call last):
File "./prgm.py", line 2, in <module>
from API.auth.module1 import authFunction
ModuleNotFoundError: No module named 'API'
This is the import statement I have in 'prgm.py':
from API.auth import module1
This question is a bit different from previous ones because I am trying to get a python script that is already in one sub-folder to access a module in another subfolder but under the same parent 'API' folder. Previous questions involved the python script being based in the parent folder and calling modules located in sub-folders.
If you really need to run API/subfolder/prgm.py which in turn import API/auth/module1.py
In prgm.py you could add a parent directory (which is 'API') to sys.path like this:
import os, sys, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
And now you could import anything from inside of 'API':
from auth import module1
try """from . auth import module1""" may be?

How to import submodules from relative path?

I have multiple modules in my project and specify some execution point. But when I try to import files from submodules, it doesn't work.
So, how to specify submodules to execute from selected execution file?
project
--bin
---- executeFile
--modules
---- __init__.py
----fileA.py
in executeFile, I try:
from ..modules.fileA import *
but get the error:
Traceback (most recent call last):
File "./bin/muexecute", line 10, in <module>
from ..modules.os import *
SystemError: Parent module '' not loaded, cannot perform relative import
I found solution.
The problem was in my opinion about using init.py.
I placed in executable scripts path to including and it works fine
PACKAGE_PARENT = '..'
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))
So you are having trouble defining your relative path, correct? Try the following:
from sys import path
path.append('C:\\realative_path')
from function_file import required_function
Hope that helps.
All modules you want to import should in in your PYTHONPATH. Therefore there is no hierarchy.
In your case It seems to me that an __init__.py is missing from your project's main folder (with all the models included), so executefile doesn't know about your modules.

Categories

Resources