ImportError with absolute and relative imports - python

Having trouble importing with a very simple file structure.
My file structure looks like this:
project/
...
project.py
helper.py
__init__.py
...
Within project.py is the class I am trying to import in helper
#project.py
class MyAPIOne():
...
class MyAPITwo():
...
#helper.py
import MyAPIOne
if __name__ == "__main__":
api = MyApiOne()
...
When running with python3 helper.py:
If I keep the absolute import import MyAPIOne I recieve ModuleNotFoundError: No module named 'MyAPIOne'
If I change it to a relative import from . import MyAPIOne I receive ImportError: cannot import name 'MyAPIOne'
I have also experimented with appended to sys.path various directories, with no luck.

If you are running this script from the project folder, you can alter your import the following way: from project import MyAPIOne.
Also, you can add this folder to your PYTHONPATH env variable.
Upd: to add some folder to PYTHONPATH you can ran
export PYTHONPATH="${PYTHONPATH}:/my/other/path"

main file can import all the files, but main file can't be imported by other files.
once file mentioned with __name__ = "__main__", then it becomes main file. so helper.py is acts as main file. it can't be imported.

Related

Import script from another script in python

I have imported a repo using git and when I try to run a file, it shows that "it could not be resolved".
The running script has:
import craft_utils
import test
import imgproc
import file_utils
The imported things are all script.
I have attached the screenshots for the error and hierarchy.
How can I solve this? Thanks.
try adding an empty file named __init__.py in the root folder CRAFT-pytorch (instead of the basenet folder)
create a empty file named __init__.py
it would solve the issue
Add a file inside of the folder called __init__.py
First you need to create an empty file named __init__.py in the folder CRAFT-pytorch
Second add these line at the top of the file you're trying to running, before the imports:
import os
import sys
import inspect
app_path = inspect.getfile(inspect.currentframe())
main_dir = os.path.realpath(os.path.dirname(app_path))
sys.path.insert(0, main_dir)
import craft_utils
import test
import file_utils

ModuleNotFoundError: Even with __init__.py file

I have 3 python file :
test.py
modules(folder) and in modules there 3 to files : module1.py module2.py init.py
test.py
./test.py
./modules
./modules/module1.py
./modules/module2.py
./modules/__init__.py
module1.py:
from module2 import temp
def print_temp():
print(temp)
if __name__=='__main__':
print_temp()
module2.py
temp =1
test.py
from modules.module1 import print_temp
print_temp()
When I run python test.py I got ModuleNotFoundError: No module named 'module2'
How can I fix that please?
When you import a module in Python, it searches the PYTHONPATH for a module / package with that name. But it doesn't search inside directories so you have to specify.
If you want to be able to run modules.module1 directly (as well as import it) then you must use the full path:
from modules.module2 import temp
But if you just want to be able to import the module and not run it directly it is better to use a relative import as it will still work even if the name of the package is changed:
from .module2 import temp

Relative imports in python with local ang global libraries

My apps are organized like this:
apps/
code/
libglobal/
funglobal.py
tests/
project/
liblocal/
funlocal.py
main.py
In main.py I have:
import liblocal.funlocal
In funlocal.py I try to import funglobal.py with:
from ....code.libglobal import funglobal
When I run
python3 -B tests/project/main.py
I get an error:
from ....code.libglobal import funglobal
ValueError: attempted relative import beyond top-level package
I have read a lot of information about relative imports with python3 and still don't find how to solve this error without changing the apps organization radically. Any solution?
As the script being executed has its __name__ set as __main__ and defines itself to be on the top level of the package, it refuses to recognize scripts in sibling directories.
You can fix this with a sys.path hack:
import sys, os
sys.path.insert(0, os.path.abspath('../..'))
or an interseting alternative with setuptools is presented in this answer.
Have you a __init__.py script in each folder ?
If no, you should create an empty script named __init__.py in each folder.

Importing from parent directory gets error

The project structure on my local machine is setup like this:
python/
__init__.py
readText.py
testing/
__init__.py
removeDuplicates.py
In removeDuplicates.py I am trying to import as follows:
from python import readText
This gives: ImportError: No module name 'python'
My init.py in both folders are blank by the way.
You need the parent directory of your python subdirectory to be present in sys.path. If you execute your script from that directory, the import should work. But the easiest way to do this is to export the environment variable PYTHONPATH.
You want to import something from the parent directory, use
from .. import readText
see relative imports:
https://docs.python.org/2.5/whatsnew/pep-328.html

Importing a module into a custom command

Suppose I have the following Django project:
/ # Project dir
/myapp # App dir
/myapp/views.py # views file
/myapp/mymodule.py # a Python module
/myapp/management/commands/mycommand.py # command file
In the views file, I can import mymodule.py by simply writing import mymodule in views.py. However, if I do the same in mycommand.py, I get the error: ImportError: no module named mymodule. I know that to import a model, I can write from myapp.models import mymodel, but mymodule is not a model, it is a separate Python module. So, how do I import this moduel into my command file?
Thats because of where mymodule is in relation to all of your other files.
If you type
from myapp import mymodule
In mycommand.py as long as you have set up your __init__.py files correctly in myapp and are using a setup.py file you should be fine. The modules documentation has more information on this
The fact that you are unable to do this means your myapp folder is not in the python's sys.path. The reason it worked in views.py is because mymodule.py is in the current directory of views.py
Assuming your Project dir (/) is in the python's sys.path:
Add a file __init__.py in myapp directory. This file can be blank.
Then you can do import myapp.mymodule or from myapp import mymodule
The same logic applies for n levels deep. If you have myapp/myappdir1/myappdir2/myfile.py you can do import myapp.myappdir1.myappdir2.myfile assuming each of these have __init__.py file in them.
Check https://docs.python.org/2/tutorial/modules.html#the-module-search-path for python's module search path

Categories