Can't import module with location set to PYTHONPATH in Python - python

I've checked other answers on SO as well, but they don't seem to be like mine.
So I'm playing around with imports, and I decided to put my module custom.py into a nested folder like this:
/Users/alex/Desktop/Learn/mods/onemore/custom.py
My main script file is in the following location:
/Users/alex/Desktop/Learn/main.py
So when I do import custom in main.py, I get the error ModuleNotFoundError: No module named 'custom'
This happens despite the fact that /Users/alex/Desktop/Learn/mods/onemore is in PYTHONPATH:
> echo $PYTHONPATH
> /Users/alex/Desktop/Learn/mods/onemore
and also the path is visible in sys.path (the second one):
> ['', '/Users/alex/Desktop/Learn/mods/onemore', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python310.zip', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages']
Why can't I still import the module?

You can import it with folder name
Ex: from onemore import custom

You need to add an empty __init__.py file at /Users/alex/Desktop/Learn/mods/onemore to call in this manner (as a regular package).
else if it's in the python path, call it as a namespace package (no need for init):
from custom import <func-you-need>
The standard for imports is currently from PEP420.

Related

Importing from directory gives ImportError

I have the following directory structure, in Ubuntu:
/Test/Foo
/Test/Foo/foo.py
If I am in /Test, and I run python from the command line, followed by from Foo import foo, I get the following error: ImportError: No module named Foo.
But this is very confusing, since according to here, one of the directories used to search when importing is the directory from which the script was invoked. If I print out sys.path though, it does not include /Test, it just includes other standard Python directories.
Any idea what is going on?
If I'm getting you right, what you are trying to achieve here is the Foo to be a package and foo be a module.
Since Foo is not made into a package (You don't have __init__.py in the directory), it is not recognized as a package and thus not imported.
When you move into /Test/Foo, then you are simply importing the module foo, which will work.
What you possibly need to do here is to create an __init__.py file inside /Test/Foo and then import the module from the package.
Or you can try relative imports. Something like from .Foo import foo.
If you just need a function try this (python 2.7):
sys.path.insert() inserts the directory specified in the path python uses to find files.
commify.py is a file in subdirectory xyz that contains a function commify(value)
import os
import sys
sys.path.insert(0, os.getcwd() + r'\xyz')
from commify import commify
print commify(12345678)
output: 12,345,678

Import classes/functions from Python files saved in same folder showing "No Module Named" error

As per screen print, import shows error in Python 3.7 version, earlier it was working fine in version Python 2.7 and I am using IntelliJ Idea.
If you see, EOC related .py files are in the same folder and have classes which are being called in Main_EOC.py by passing objects which are inter-related. It's amazing to see the red line while importing files from same folder.
Please help me why it's showing such error
"This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are supported better than instance items.`"
Also, if you see the line which have full path, is not showing error
from EOC_Module.eoc.script.config import Config
Please help me if there is a way to add this full path on top of the code or other option.
The behavior of import path search changed between python2 and python3. The import path always includes the directory from which the main module was loaded, but it no longer includes directories from which modules were imported.
You need to change your import statement syntax as follows, if you want to import a module that lives in the same directory as the module in which you do the import:
# old way, import works if the named module is in this module's directory
import x
# new (Python3) way:
from . import x
For the second part: adding a path so all code can import from a certain directory: if that directory is (and will always be) relative to your main: you can add a few lines in the main module to make it available. Something like this:
import sys # if you haven't imported it already
import os.path
home = os.path.dirname(sys.argv[0])
sys.path.append( os.path.join(home, "EOC_Module/eoc/script") )
# now, you can import straight from the script directory
import EOC_Intraction
When using pycharm the root directory for your python executable is the same as the root directory of your project, this means that python will start looking for files in the root directory with this files:
.idea/
EOC_module/
logs/
reports/
sql/
This is the reason of why: from EOC_Module.eoc.script.config import Config works.
If you execute your code from the terminal with: python3 Main_EOC.py (not pycharm) the root directory for your python will be the same as the one containing the file, all the other imports will work but from EOC_Module.eoc.script.config import Config not.
So you need to make your imports from project directory if you are using pycharm.

No module named "file1.py"; test1 is not a package

I'm trying to modularize my code and I'm having issues with it.
My folder is constructed like this:
code
|_main.py
|_test1
|_calcA.py (which contains a method)
|_test2
|_calcB.py (which contains another method)
|_test3
|_calcC.py (which contains another method)
Now my main.py contains these lines:
import sys; import pprint
pprint.pprint(sys.path)
from test1.calccircle.py import calcA
from test2.calctriangle.py import calcB
from test3.calccarre.py import calcB
The following error comes:
ImportError: No module named 'test1.calcA.py'; 'test1.calcA' is not a package
You don't need to specify .py while importing modules. Python knows your modules are Python code only. So remove .py while importing modules in Python.
Test1 is a folder or directory and you are trying to access it like a package.
If you want to access it that way you have to insert init.py file in your folder. And also you don't need to specify .py when importing!
add __init__.py inside your directories
You can do like this
from test1.calcA import calcA where calcA can be a method.

ImportError: No module named even after I appended to system path

I have the following files:
./ElementExtractor.py
./test/ElementExtractorTest.py
In ElementExtractorTest.py, I am trying to import ElementExtractor.py like this:
import sys
sys.path.append('../')
import ElementExtractor
However, I am getting:
ImportError: No module named 'ElementExtractor'
How come it's not seen?
Is there a simple way to import another class with a relative reference?
The general answer to this question should be don't, I guess. Messing with relative paths means that the path is relative to the place from where you're calling it. That's why PYTHONPATH is worth embracing instead.
Let's assume, your directory structure looks like this:
./projects/myproject/ElementExtractor.py
./projects/myproject/test/ElementExtractorTest.py
Now, you're calling your script like this:
[./projects/myproject]$ python3.5 ./test/ElementExtractorTest.py
Your current directory is myproject and in ElementExtractorTest.py you're adding ../ directory to sys.path. This means, that ./projects/myproject/../ (i.e.: ./projects) is effectively added to your PYTHONPATH. That' why Python is unable to locate your module.
Your code would work from test directory though:
[./projects/myproject/test]$ python3.5 ./ElementExtractorTest.py
Now, by adding .. to sys.path you are effectively adding ./projects/myproject/test/../ (i.e. ./projects/myproject) to sys.path, so the module can be found and imported.
my folder structure
./test.py
./Data.py
from test.py
import Data
obj = Data.Myclass()
update
in your case
from ..ElementExtractor import MyClass
Hope this helps :)

Python - fails importing package

I have trouble importing package.
My file structure is like this:
filelib/
__init__.py
converters/
__init__.py
cmp2locus.py
modelmaker/
__init__.py
command_file.py
In module command_file.py I have a class named CommandFile which i want to call in the cmp2locus.py module.
I have tried the following in cmp2locus.py module:
import filelib.modelmaker.command_file
import modelmaker.command_file
from filelib.modelmaker.command_file import CommandFile
All these options return ImportError: No modules named ...
Appreciate any hint on solving this. I do not understand why this import does not work.
To perform these imports you have 3 options, I'll list them in the order I'd prefer. (For all of these options I will be assuming python 3)
Relative imports
Your file structure looks like a proper package file structure so this should work however anyone else trying this option should note that it requires you to be in a package; this won't work for some random script.
You'll also need to run the script doing the importing from outside the package, for example by importing it and running it from there rather than just running the cmp2locus.py script directly
Then you'll need to change your imports to be relative by using ..
So:
import filelib.modelmaker.command_file
becomes
from ..modelmaker import command_file
The .. refers to the parent folder (like the hidden file in file systems).
Also note you have to use the from import syntax because names starting with .. aren't valid identifiers in python. However you can of course import it as whatever you'd like using from import as.
See also the PEP
Absolute imports
If you place your package in site-packages (the directories returned by site.getsitepackages()) you will be able to use the format of imports that you were trying to use in the question. Note that this requires any users of your package to install it there too so this isn't ideal (although they probably would, relying on it is bad).
Modifying the python path
As Meera answered you can also directly modify the python path by using sys.
I dislike this option personally as it feels very 'hacky' but I've been told it can be useful as it gives you precise control of what you can import.
To import from another folder, you have to append that path of the folder to sys.path:
import sys
sys.path.append('path/filelib/modelmaker')
import command_file

Categories

Resources