If I have a module in my project with all the inits configured properly and I try to import anything from this module, PyCharm does not identify what I am trying to import. It would work before but somehow it stopped working and I have no idea why.
Example:
./package/file.py
def function():
print('function')
./package/__init__.py
from .file import function
./call.py
from package import function
function()
The code executes fine but I can't use auto complete and the editor is informing an error "Unresolved reference 'function'" in the file ./call.py
Methods I tried that did not work:
Invalidate Caches / Restart
Use different the interpreter (but still using conda)
CTRL + Space doesn't show anything I need
Tab doesn't show anything I need
Restart PyCharm
EDIT0:
If I use import package the autocomplete works fine displaying the functions (package.function) to use while in the Python Console, but still doesn't work in the editor.
EDIT1:
I tried to mark the directory as Source Root and it did not work
EDIT2:
Tried uninstalling from snap and installing it all back again after removing all files from /home/usr/.PyCharm* and it is working fine.
You need to mark top level directory as a Source Root.
Right-Click on it, and at the bottom there is an option Mark Directory as and choose Sources Root. It will turn blue.
Then you can import:
from package import function
function()
OR
import package
package.function()
Read more at here.
Tried uninstalling from snap and installing it all back again after removing all files from /home/usr/.PyCharm* and it worked fine.
Related
There are loads of answers on how to import modules from other folders.
The answer always seems to be along the lines of:
import sys
sys.path.insert(0,"c://UserName//MyFolder//MyBeautifulCode")
import myscript as ms
after which you can run ms.my_fun(x,y,z) where my_fun() is defined in c://UserName//MyFolder//MyBeautifulCode//myscript.py
The code runs; however, what doesn't work is that, this way, I do not get the usual tooltip showing the arguments of my_fun(); if instead I copy myscript.py in the very same folder as the script I am currently running, then, yes, I do get the tooltip.
What I mean is I don't see something like this:
I have tried with both PyCharm and Spyder and the behaviour, in this respect, is the same for both.
I suppose this happens because c://UserName//MyFolder//MyBeautifulCode//myscript.py gets added to the path only when the script is run so, before it is run, the IDE doesn't find my_fun()
Is this correct?
If so, is the only solution to manually add c://UserName//MyFolder//MyBeautifulCode//myscript.py to the path ?
By the way, I am talking about a couple of functions which I reuse in 3 separate programs I am running. It is nothing worth publishing on github or pip as a package or anything like that.
For PyCharm, you need to set up your project's venv settings to include that path as well. It took me a lot of time to find it at first - and I used google to search for this! but apparently PyCharm hid the option deeper... well, see for yourself.
Go to the Settings, Project: [your project name here], Python Interpreter
See the cog on the right? Click it, "Show all". This will show up, listing all venvs that PyCharm can use for your project:
With your venv selected, click the last icon at the bottom. The icon looks kinda like a folder structure.
Now we see all the paths recognised by the selected interpreter in PyCharm. We can click + to add a new path. Manually added path will have "(added by user)` at the end, just like in the pic.
If you insert a path into the Python path in your code, it's only interpreted at runtime. To get your IDE to know about your library, you will have to add it to the Python Path, e.g. like described in this question: https://stackoverflow.com/a/55209725/5660315.
Running PyCharm 2020.1.2 Community Edition in Win10 with a Python 3.6 venv as interpreter. Installed the package feature-engine through the Project Interpret interface, installs fine and appears in the list. I can successfully import feature_engine in the PyCharm console, and I can use it fine. I can also execute a .py file with this import statement in the Terminal with the venv activated, and it also works fine. However, when I try to Run the same .py file with the import statement, I get:
ModuleNotFoundError: No module named 'feature_engine'
I have tried using import and importlib, thinking the issue was the hyphen, but those didn't work. I have tried uninstalling and reinstalling, restarting PyCharm, etc. Nothing seems to work. Any suggestions how to get the Run function working?
EDIT: Thanks for the suggestions. Attached are the Run configuration and the Project interpreter configuration. As far as I can tell, the environment is the same.
Below are examples of the error trace. The object being Run is a Flask app, which imports packages that use the feature-engine library. The actual import statement in the final import is simply import feature_engine. Trying to import the method directly using from feature_engine import variable_transformers as vt also fails.
Make sure you're using the right configuration to build your program (that is, using the python executable of the right enviroment). You can check this in the top right corner, where the run button is.
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
I have a problem getting PyDev on eclipse to recognize already installed modules. Here is my detailed approach. The machine is a Mac (Snow Leopard).
In terminal the command
python --version
shows Python 2.6.6.
import unidecode
and
from unidecode import unidecode
work both fine!
I installed PyDev in Eclipse and went to configured the python interpreter (Auto Config). I selected all the proposed packages and hit Apply and Ok.
But eclipse keeps complaining
Traceback (most recent call last):
File "/Users/me/Documents/workspace/myproject/python/pythontest.py", line 12, in <module>
from unidecode import unidecode
ImportError: No module named unidecode
The python file looks like this
#!/usr/bin/env python
# encoding: utf-8
import sys
import os
from unidecode import unidecode
def main():
print unidecode(u"Ă…got Aakra")
if __name__ == '__main__':
main()
When I remove the first line in the script
#!/usr/bin/env python
it results into the same error.
Does someone know where the problem lies?
This is the solution to my problem:
Find out the path to the folder ../site-packages/ of your corresponding python version. ( For me it was /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/ for python 2.6 on my Mac with Snoe Leopard.)
Open eclipse preferences and go to PyDev -> Interpreter - Python.
On the left side of the lower box, click on New Folder.
Add the navigate to ../site-packages/ of your corresponding python version.
Hit open.
Hit Apply.
Hit Ok.
And you should be good to go. =)
Thanks #all particionts, who provided hints into the right direction in the comments.
I ran into the same problem just today. I am using pydev and had a working project with a number of sub-packages. Suddenly after having created a new module I was not able to use this module in a different package. The puzzling feature was that I could use another module in the same sub-package...
Finally after
eclipse restart
remove/add python interpreter and all site-packages
annoyed head-scratching
I deleted all compiled classes with the following script:
import os
def clean_folder(folder):
for file in os.listdir(folder):
path = os.path.join(folder,file)
if os.path.isdir(path):
clean_folder(path)
if '.pyc' == file[-4:]:
print 'deleting: ' + str(path)
os.remove(path)
if __name__ == '__main__':
folder = 'YOUR_PROJECT_SRC_PATH'
clean_folder(folder)
and finally I can do 'actual' work :)
Hope it helps somebody...
You can simply add the module to the pydev path. Go to project properties (from the context menu) -> PyDev -> PYTHONPATH -> External Libraries. Depending on whether the module is in a source folder or a zip/egg file, select either Add source folder or Add zip/jar/egg. Navigate to the site-packages directory and point to the relevant file or folder (mine is: /usr/local/lib/pythonx.x/site-packages)
Try preferences > pydev > interpreter - python and removing and re-adding the python interpreter (make sure you know the path to it before you delete it), when you re-add it tick all the boxes.
When Eclipse gets 'lost' with respect to what packages exists on your system or in your project, from the context menu of your project, choose 'Properties' menu item, then the 'PyDev - PYTHONPATH' item in the treeview on the left of the dialog, then the 'Force restore internal info' button. Seemingly, PyDev keeps a computed cache of the info and when for any reason the cache becomes incoherent, you can force PyDev to recompute.
In my case I was not getting this error before compiling, but when I compile I got the error ImportError: No module named myant.core. I tried to add the files from PyDev-PYTHONPATH, but again I got the same error. Then I realized that I actually do not have to add the path exactly to the folder where my .py files are located. Infact I have to add the folder where myant.core is located. After doing this I did a restart when I recompiled my project again, the problem was fixed. I would share that I have:
Python 2.7 Eclipse kepler 4.3, PyDev 3.9.2 and on my ubuntu 14.04
.py files location:/${PROJECT_DIR_NAME}/src/myant/core, therefore I added /${PROJECT_DIR_NAME}/src
#Aufwind your answer above helped but didn't solve for me.
Find the path to the folder ../site-packages/ ....
Open eclipse preferences and go to PyDev -> Interpreter - Python.
On the left side of the lower box, click on New Folder.
---> here I departed from your instructions. I added the egg for the module that wasn't being recognized. Adding the site-packages folder didn't fix it.
Hit open.
Hit Apply.
Hit Ok.
And then I was good to go. =)
Open eclipse window -> preferences and go to PyDev -> Interpreter.
click on 'Check if interpreters are synchronized with environment'
This did it for me. No Eclipse restart was required.
I fixed this problem by going to the project properties -> PyDev Django
and setting the Django settings module.
For Oxygen 2 (I think it worked on earlier versions, too)...
Right click on project folder and select "Properties"
Select "PyDev - Interpreter/Grammar"
Click on "Click here to configure an interpreter not listed"
Select any existing interpreter from the top list of configured interpreters
A "Selection Needed" dialog should appear where you must select one or more interpreters to restore. Check all that apply
Click "Ok" and PyDev will rescan, and I assume, rebuild some internal view of your site-packages
Click "Apply and Close" to close all dialogs
To make the import error markup disappear in my code editor, I need to type a space after the offending import then save the change. The import error then disappears because PyDev can now find the offending import module.
Suppose your eternal module is in /.
Launch Eclipse and go to the project option. Select "PyDev-PYTHONPATH"
and on the right you will see a tabbed window. Select External Libraries there.
Click on Add Source Folder and select your library from the above path.
I downloaded beautifulsoup.py for use on a little project I'm making. Do I need to import this .py file in my project?
Do I just copy and paste the code somewhere inside my current python script?
Thank you for the help.
I found this but it doesn't say anything regarding Windows.
http://mail.python.org/pipermail/tutor/2002-April/013953.html
I'm getting this error when using it. I copied and pasted the .py file to the folder where my project was on Windows Explorer, not this happens. Any suggestions?
If it's in the same directory as your little project, all you should need to do is:
import BeautifulSoup
If you are keeping it in some other directory, the easiest way to do it is:
from sys import path
path.append(path_to_Beautiful_Soup)
import BeautifulSoup
Python keeps track of where it is currently, and first looks in the current directory. Then it checks through all of the paths in sys.path for the module in question. If it cannot find it in any of those places, it throws an error.
When you install beautifulsoup the canonical way (with easy_install for example, or with a windows installer, if any) the beautifulsoup module will probably be added to your PYTHONDIR\lib\site-packages directory.
This means
import beautifulsoup
should do the trick.
Otherwise, adding beautifulsoup.py (if it's a single file) to your current project directory and then issuing import beautifulsoup should also do the trick.
You have several choices:
you can cut and paste in the code, assuming the license permits etc. however, what happens when the code is updated?
you can put the code into the same directory (ie folder) as your code. Then all you need to do is say import beautifulsoup before you try to use it.
you can put the code somewhere in the python load path.
I've done it before, putting BeautifulSoup.py inside the same directory as the script and import it would work. If you have multiple scripts spread over different directories, put the beautifulsoup file in the root directory and do a relative import.
you have to install a new package correctly in python by using in the command line:
pip install BeautifulSoup
if you don't know the name of the package use :
pip search beautiful
and the pip will get all package that have "beautiful" in their name or description ...
One more thing that is very important ; and because you use eclipse (netbeans it's the same) and pydev as i can see; you should refresh the list of package used by pydev when installing a new package by going in the menu to (for eclipse) Window -> Preference -> Pydev -> Interpreter - Python and clicking on Apply why is that ?, so that you can use the full power of pydev correctly (code completion , F3 ...) and because Pydev don't know if a package has been added until you tell him so.
the steps are for eclipse you can do their analog in netbeans right ?