why python not recognizing my project packages in import statements - python

I'm trying to import my packages from the same project I am using. But I'm getting ImportError: No module named main_package.sub_package
I'm using python2.7
My project structure is
my_project/main_package/sub_package/file_a
my_project/main_package/sub_package/file_b
and the following row:
from main_package.sub_package import file_b
isn't working when we add it in file_a. and isn't working from other packages in main_package.
This does work on other computers.
I tried to add all of their elements to my sys.path.
I also have anaconda installed in my computer, and I tried to use the following interpreters: ~/anaconda/bin/python2.7, ~/anaconda/bin/python, /usr/bin/python2.7.

In the project there should be src directory. In your case my_project/src/main_package/.
Inside IDE (I use PyCharm) right click on it and select "Mark Directory As" -> "Sources Root".

Related

VS Code import resolution error with Pylance (ModuleNotFoundError)

Having an import resolution error with pylance not recognizing packages. (Windows 10)
Venv activated on the local directory
Confirmed pip -list that the package is correctly installed
Ran VS code as administrator
Checked the package is installed in the /Lib/site-packages folder for my python installation
Receiving the error:
ModuleNotFoundError: No module named 'abc123'
Inside the file, hovering over the broken import says
"packageFoo" is not accessible
Import "packageFoo" could not be resolved Pylance
I found many similar questions, but not this specific answer.
In vscode, locate the file dropdown on the top toolbar.
Select preferences > Settings (Ctrl +)
In the search bar, search for pylance
Scroll down to Python > Analysis: Extra Paths
Click 'add item' button
Next step you need to identify the installation path for python in windows. In that path there is a 'Lib' folder. Under lib folder there is a 'site-packages' folder. This is the folder for all your pip installed packages.
For me it looked like this:
C:\Users\user_name_here\AppData\Local\Programs\Python\Python310\Lib\site-packages
Copy this path and add it as the item in the pylance vscode settings.
Additionally: You can open the 'Python > Analysis: Indexing' settings below to edit a JSON file. Here you copy and paste the same path, with extra '' - backspace escape characters. Noting there is a comma after the first entry, if it exists.
If you have correctly installed Pylance when you open a .py file, this extension would be activate. Now check settings.json file and add the following sentence:
"python.languageServer": "Default" or "Pylance".
 It is probably that your problem is caused because Pylance is not pointed to the path where is your library installed or another package and the error is originated (ModuleNotFoundError: No module named 'abc123'), then you may need to verify in your settings.json this configuration:
python.analysis.autoSearchPaths : true
python.analysis.stubPath:./typings
python.analysis.extraPaths:["./folder"] (if your project use a specific folder)
python.analysis.autoImportCompletions:true
Make sure there is a .py extension on the module.

Python import custom issue

I'm new to python. I have a problem with importing from different relatively folders. PyCharm suggested that I use python.foldername and it uses python as root package which is positioned in my root folder of project. It worked when I ran my main.py from pycharm
But when I use terminal to run the same file, it broke and it can't work out python.foldername. And I can't import from parent directories
My question is how do I make my root folder as a package like pycharm did
So the answer is to add it to your python path in your environment/virtualenv.
For heroku see: https://devcenter.heroku.com/articles/getting-started-with-python#introduction

PyCharm unresolved reference when importing class from other file

This problem has been driving me nuts. I am trying to import a class from a file in the same directory. PyCharm is giving me the "Unresolved reference" error. MyClass is defined in file.py.
I have found these questions:
Unresolved reference issue in PyCharm
Pycharm: "unresolved reference" error on the IDE when opening a working project
PyCharm shows unresolved references error for valid code
Unresolved reference when importing from sibling sub-package with
I have the following project structure:
I have marked src as the sources root...
I have set the "Add source roots to PYTHONPATH":
I have tried File -> Invalidate Caches / Restart.. (I even restarted the computer).
If I try to run it, I get the following error in the console: ImportError: cannot import name 'MyClass'
The interpreter is a virtualenv on Python 3.4 on Ubuntu x64 14.04.
If I install and import any 3rd party packages, they work fine.
If I try echo $PYTHONPATH in the terminal it returns nothing (same with env | grep PYTHONPATH. I have the appropriate virtualenv active when I try these.
Any clues?
If MyClass is defined in pack/file.py, you need to import it as:
from pack.file import MyClass
Note that using names of Python built-in types (such as file) for your own modules is a bad idea.
If you are using python version 3 try this
from .pack import myclass
This worked for me
The following steps solved my issues:
All directories required at least a blank __init__.py file
Mark all directories as source roots (per previous poster instructions)
Yes, if you are using python 3 you should add something like this:
from .pack import MyClass
It will work
I had the same issue when I tried to import a new class, however I could successfully import functions from a file in the same directory. I still dont understand why I could not import my class but thought I would share the information for other users.
#kaylebs response worked for me. However I then added the src directory to the list of source directories, first link in #lulian 's question and could remove the '.' from my file name.
There are several reasons why this could be happening. Below are several steps that fixes the majority of those cases:
.idea caching issue
Some .idea issue causing the IDE to show error while the code still runs correctly. Solution:
close the project and quick PyCharm
delete the .idea folder where the project is. note that it is a hidden folder and you might not be aware of its existence in your project directory.
start PyCharm and recreate the project
imports relative not to project folder
Relative imports while code root folder is not the same as the project folder. Solution:
Find the folder that relative imports require in the project explorer
right click and mark it as "Source Root"
Editor not marking init.py as Python
Which is the most illusive of all the cases. Here, for some reason, PyCharm considers all __init__.py files not to be python files, and thus ignores them during code analysis. To fix this:
Open PyCharm settings
Navigate to Editor -> File Types
Find Python and add __init__.py to the list of python files or find Text and delete __init__.py from the list of text files
I just delete the copied the code and delete the file and again create the same, that time it will work

Import Error in Eclipse when importing same name packages

I have a pydev project opened in eclipse.
The project's packages nesting is as follows:
my-package:
my-sub-package:
foo
In this project I am using an import from another project I created.
The other project's nesting is:
my-package:
my-sub-package:
bar
So the 2 main packages have the same names.
When trying to import:
from my-package.my-sub-package import bar I get ImportError: No module named bar.
I guess that happens because eclipse is searching in the current project and when it doesn't find bar, it doesn't look for it in dist-utils (where I pip installed the project I'm trying to import from).
(When trying to do the same import from a regular python opened from the same location, the import works perfectly fine - so it's something in eclipse).
Is there a way to tell eclipse to continue searching for the module in all folders in the pythonpath (so it can reach dist-utils), even when the packages have the same name and it didn't find the right package in the current project?
Thanks a lot.
Where are you running the regular python from exactly?
If you have
src-root:
my-package:
__init__.py
my-sub-package:
__init__.py
foo.py
and you run the regular python from within src-root then you will get the same result ie that it will not work but if you run it anywhere else it probably will work as you say.
If you can't rename any of the packages the only thing is to remove the current scr-root from the 'Source Folder' in your eclipse PyDev options but not would mean you would never access the foo my-package again.
See http://docs.python.org/2/library/sys.html#sys.path

IntelliJ Python plugin & Run classpath

I have a project located at /home/myself/workspace/Project1, for which I created an SDK from a Python 2.7.3 Virtualenv I have setup.
This project uses some external code that I have in an accessible directory, e.g. /home/myself/LIBRARY; this directory contains several directories with code, docs etc....
For example, there is a module "important_util" located at /home/myself/LIBRARY/mymodule/important_util.py.
Now, I added the whole dir /home/myself/LIBRARY in the SDK Classpath, and in the Editor window it appears just fine. The imports and calls are recognized and I can also navigate through the code in LIBRARY directories.
The problem is that, when I try to run my program, it fails at the first import using LIBRARY!!!
Traceback (most recent call last):
File "/home/myself/workspace/Project1/my_program.py", line 10, in <module>
from mymodule import important_util as ut
ImportError: No module named mymodule
I also tried to add the same directories to the section "Global Libraries" in the Sources section...but no luck.
I can't seem to find a way to add this code to the Run classpath, how would I be able to do this?
Make sure you have __init__.py in mymodule directory:
The __init__.py files are required to make Python treat the
directories as containing packages; this is done to prevent
directories with a common name, such as string, from unintentionally
hiding valid modules that occur later on the module search path. In
the simplest case, __init__.py can just be an empty file, but it can
also execute initialization code for the package or set the __all__
variable, described later. ©
UPDATE: In IntelliJ IDEA additional directories should be added as Module Dependencies or configured as Libraries (to be added to the Dependencies) instead of the Classpath tab of the Python SDK:
I've verified that this folder (D:\dev\lib) is added to the PYTHONPATH and import works.
In IntelliJ 14 it's a little different, you are modules/eggs like so:
Go to File -> Project Structure
Now select Modules and then "Dependencies" tab
Click the "+" icon and select "Library"
Click "New Library" and select Java (I know it's weird...)
Now choose multiple modules / egg and "OK".
Select "Classes" from categories.
Give your new library a name, "My Python not Java Library"
And finally click "Add Selected"
From Version of 2017.1 adding it has been changed again. There is no project structure in the file menu. Writing current procedure down:
Go To Preference/Settings. File -> Settings (IDE Name -> Preferences for macOS)
Select Build, Execution, Deployment
Select Python Interpreter
Select on drop-down menu of project interpreter and select the path of path of version of Python required for the project.
Click on Apply and wait for few minutes to let IntelliJ index the python packages.
All error should be gone now and You should be able to see Python used in the project in the list of external libraries.
Happy Coding.

Categories

Resources