Before, when I would instantiate a class that I haven't imported, I would be able to hover over the class (or whatever was missing), and see an option to import it like the screenshot
Where it says "Create class" I would have the option to import the package. Since I updated my pycharm to 2021.3.1, that option seems to be gone for external packages. It still seems to work for internal packages, say, json. This is vital to my productivity. Has anyone else run into this?
I ended up deleting and recreating my .idea directory in pycharm. Once I did this, the problem was resolved.
Related
I have a question regarding simple imports that I cannot get my head around.
Take a look at the attached screenshot to see my project layout.
The file somefile.py imports the class SayHello from a file called someclass.py and calls it. someotherfile.py does the exact same thing. They both use from someclass import SayHello.
In Pycharm both files run. However, From the command line or from VSCode somefile.py runs, but someotherfile.py errors out with the following error:
ModuleNotFound: No module named 'someclass'.
I believe it has something to do with PYTHONPATH/environment variables or something like that, but every explanation I have read has confused me thus far (Even this one which I thought was going to set me strait Relative imports for the billionth time).
Can someone explain in simple terms what is happening here? What is Pycharm doing by default that other editors are not such that my imported modules are found? How can I make someotherfile.py work in VSCode without modifying it?
Thanks in advance!
Pycharm adds your project directory into python paths by default. See configuration of "Pycharm run" that you execute and you shall see few checkboxes like
If those checked Pycharm creates PYTHONPATH environment variable for you that instructs Python where to look for someclass module.
You will have to configure VSCode to define PYTHONPATH environemnt variable for python command you run and include your root project directory path on it.
TLDR: Mess with the line starting with ./automated pointing it to various directories in your project until it works haha.
Long rambling answer: Alright now that I am not in a frenzy from trying to figure this out and it has been a day, I feel like I can make a conherint response (lets see if that is true).
So my original answer was an attempt to simplify my problem into what I thought was the issue due to a ModuleNotFound error I was getting. I had been trying to get unittests in Python inside of Visual Studio code to work (hint hint just use Pycharm it just works out of the box in there), but the integrated testing feature or whatever could not find my tests giving ModuleNotFound as the reason.
The solution to my problem actually just concerned the line ./automated-software-testsing-with-python/blog.
In the below screenshot the relevant part is ./automated-software-testing-with-python/blog.
This is it when it is correctly configured (My tests work Woo hoo!)
Now you can go ahead and read the official documentation for what this line is doing, but I am convinced that the documentation is wrong. Due to how my code is structured and how my files are named, what the documentation says its looking for definitely does not exist. But that is another can of worms...
I actually got it to work by accident. Originally when you go though the wizard to set up what's in that screenshot above, it defaulted to ./automated-software-testing-with-python which did not work. I then manually edited it to something else that was not the below screenshot hoping to get it to work.
It was only when I pointed it to that blog directory on accident (thinking I was in a different file due to trying to debug this for hours and hours in a blind rage) that it ended up working.
I did a bunch of PYTHONPATH manipulation and Environment Variable mumbo jumbo, and I originally thought that that had an effect, but when I cloned my repot to my other machine (which did not have any of that Environment Variable PYTHONPATH stuff going on) it worked too (again, provided that the line in question pointed to blog.
Ok hopefully that might help somone someday, so I'll end it there. Not to end on a bitter sounding zinger, but I will never cease be amazed by how doing such simple things such as configuring the most basic unit test can be so difficult in our profession haha. Well now I can start working. Thanks for the help to those who answered!
I am able to refactor variables in VScode, but I would like to refactor the module names so that the import of those modules are automatically resolved.
A similar feature is present in JetBrains Pycharm but I could not find in VScode.
Such a feature doesn't exist in the Python extension for VS Code. To request it, open an issue at https://github.com/microsoft/vscode-python .
Update: This issue has been raised in issue 4628. The feature still doesn't exist for now, but hopefully it will soon.
I just have a quick question about an error I've been getting when I try to import:
from psychopy import gui
So if I try to import this code in one program I have no problems, however, if I try to import it in another I get:
"ImportError: cannot import name gui"
Does anyone know why this might be happening? Why does it work for one problem, but not the other? Also, I feel like it wasn't doing this before, and it just started suddenly. Any advice would be greatly appreciated.
UPDATE: I think Jon's answer is the correct one. If I was right, you should get an error "no module named psychopy".
Given that you tagged this question with the psychopy tag, my guess is that it works if you run it from the psychopy app and that it doesn't work if you run it from another editor or command line.
The reason is that psychopy is currently shipped as a bundle that comes with it's own python and a lot of modules/dependencies, including psychopy. The system is not made aware of these modules via the PYTHONPATH.
You can make them available system-wide by either (1) following the steps outlined here or (2) use the conda based installation described in this post in the psychopy-dev list. The latter feature is still work in progress but will probably eventually mature to be the default install option.
I think the other answers are wrong ;-)
I think if you had a different virtual environment or installation then the error in your code would indicate "No module named psychopy"
The fact that it finds something called psychopy but no sub-module called gui is a different problem. Often this occurs if you have a folder or file called psychopy next to you current working directory (eg. next to where you launch the script). Then Python thinks that's the psychopy module but can't find gui within it.
So, do you have a folder called psychopy? Rename it psychopyStuff.
I think you are using different virtual environments for both the projects, and so the package is installed in one virtualenv, and not in the other.
To verify this is the case, do a pip freeze in both the projects and compare the results.
If there is a single environment, the output will be same, otherwise the outputs will be different amongst the two.
I've lost count on how many articles I've read both here on SO and elsewhere, but even after trying all suggestions I've had no success, so I decided to post my specific question here.
I'm on OSX (10.9), I have a Python 2.7 installation on a virtualenv (besides the global one) and Aptana Studio 3. I've tried all sorts of set ups, but I got to my current configuration by doing:
File > Import > General – Existing folder as new project
I then right-clicked the project directory and selected PyDev > Set as Django Project. I chose my manage.py and settings file.
Then I went on to Properties > PyDev – Interpreter/Grammar and clicked the hyperlink to configure an interpreter not listed. I selected the python file in my virtual environment. I was prompted with the following list of folders to choose:
If I click "apply" without changing the default, I get the following error:
If I proceed anyway, I get all sorts of import errors for standard library packages/modules (e.g. json). I went and checked the lib folder in my virtualenv python installation and indeed these packages/modules were not present, which makes me even more confused about how virtualenv works (I hate these configuration things and I admit that for a long time I have avoided them whenever I could, collaborating to the maintenance of my ignorance). I have virtualenvswrapper installed. workon env_name works perfectly, the pip installations go to the correct site-packages, but the standard library seems to be being accessed in the global python.
Anyway, I therefore included the global python lib folder:
I then went to Properties > PyDev – PYTHONPATH > Source folders tab > Add source folder, selected the root of my Django project and clicked Apply.
I went to Aptana Studio 3 > Settings… > PyDev > Code Analysis and configured it:
RESULT:
Certain things, like method( self ): (notice the spaces) are corrected on save. I don't get any PEP8 warnings for many other stuff though, like dict[ 'key' ] (extra spaces again), more than 80 characters per line etc.
I also get errors on relative imports (e.g. from ..utils import *) and consequently all lines that use the imported values.
What could I possibly be doing wrong??
Although I haven't completely solved my problem, I'm posting this as an answer because it does achieve what the title asks for.
I reinstalled Aptana and instead of importing an existing folder as project I created a Django project (New > Project > PyDev Django Project) and replaced the default new directory with my project's root. IT WORKED. I'm getting PEP8 warnings now!
There are caveats, however :
I don't know what this "create project" wizard does differently behind the scenes but as I feared it messed up with my files somehow. A git status showed almost everything deleted and a lot untracked files. I cleaned it up with a git checkout -- <project root> and git clean -f -d. That solved the problem and the PEP8 warnings are still showing.
The second problem is that relative imports are broken. I have a from ..utils import * for example. There are no error or warning on this line itself, but I get false "Undefined variable" erros in every line that uses something from this import.
According to this issue, it seems to be an open, unresolved problem with PyDev.
According to the PyDev relase history, however, Release 2.2 "Fixed issue with relative import with wildcards", which makes me very confused.
For the moment I guess I will simply hide "undefined variable" errors, since these will be caught when I actually run the code anyway. But the whole point of using an IDE is having features that catch these errors beforehand, so if anybody has some light to shed on this issue it would certainly be very appreciated.
PS: The scenario is exactly the same in LiClipse. PEP8 works now but relative imports lead to "Undefined variable" errors.
UPDATE
Here's a screenshot of the situation:
Well, the real problem is that Aptana Studio 3 has an older version of PyDev bundled (and you can't really update it separately). The virtualenv folders for the library are there, but unchecked by default in this version of PyDev (so, you can check them manually -- but in the latest PyDev this is already gotten properly).
Now, for pep8, it's a known issue that the current version of PyDev can't work with the latest pep8 (because it uses its internal Jython to run it, which is a bit old: Jython 2.2.1). This was just fixed -- it's still not in an official release, only in the current nightly build -- but should be in a final release next week (which updated the internal Jython, pep8 and added autopep8 as a code-formatting preference).
Still, if you're using Aptana Studio 3, I don't know when they're going to upgrade it to that version (I'm not sure what you use from Aptana Studio 3, but depending on your needs, LiClipse: http://brainwy.github.io/liclipse/ can be used as an alternative -- and it's always kept updated with the latest PyDev).
We are having some annoying problems with Eclipse, which apparently have been always there, on Windows 7 + a custom python installation + Eclipse 3.7 and the latest Pydev.
The problem is basically that if when setting up the python interpreter you add all the libraries too, then Eclipse or Pydev or who knows what deletes all these entries from the global easy_install.pth file, which are also configured in Pydev.
This means that within Eclipse everything works fine, but anything outside of it can't possibly work correctly.
Now I find it hard to believe that noone noticed, so I would think that we're doing something wrong.
I also filled a bug which didn't get much attention yet:
https://sourceforge.net/tracker/?func=detail&aid=3446052&group_id=85796&atid=577329
Any idea of what and why it could be?
Already being able to know exactly who and when modify that file would help a little bit, any suggested tool?
EDIT:
I'm trying with Process Monitor as suggested below.
So I fire up Eclipse, I run a simple Python command and I get something like this happened the file.
"File Time","Total Events","Opens","Closes","Reads","Writes","Read Bytes","Write Bytes","Get ACL","Set ACL","Other","Path"
"0.0000306","4","1","1","0","0","0","0","0","0","2","C:\python25\Lib\site-packages\easy-install.pth"
So basically it was open:1, closed:1, other:2.
And the file was actually modified.
My impression is that Eclipse just stupidly overwrites the file, otherwise there should be also some read operations, right?
That, however, doesn't help me that much, I can only see Eclipse as the process modifying the file, not much else.
Ok, I must say I haven't been able to reproduce this so far in PyDev... do you know if that's only happening in your machine (or some other colleague also has the same problem)?
To try to reproduce it, can you give more details on your toolchain: what's your python version and what's your setuptools version? Which packages you have installed? (my feeling is that the culprit is not really Eclipse/PyDev, but some python package that's doing that).
Just to note, PyDev simply doesn't do anything related to .pth files -- all it does is launching your python script with the PYTHONPATH setup in the environment variables for the launched process (so, it's very unlikely that PyDev is writing that file -- simply because it doesn't know anything related to .pth files).
One thing that could help in getting to the root of it: you can try making that file unwritable (you should be able to change its permissions so that you can't modify it), then, try to reproduce and see if you get some error somewhere (because if someone tries to write it, there'll be an exception because you don't get permissions to do so).
Since you are on windows, why not use process monitor? Turn it on, filter for your file(s), then install. It'll log who touches the file, and in what sequence. That should find your culprit.
I haven't really found the fix for the real problem, but at least I found a workardound.
What I do now is to store in a text file all the egg names that should be in the sys.path at run-time.
Before doing anything else I take this list, join these paths with the correct site-packages path, and add what was missing to the sys.path.
It seems to work, but if I remove some libraries (like pyqt) even if it's they are added I still get som errors, so there is still something missing...
import pkg_resources
import sys
from distutils.sysconfig import get_python_lib
from os import path
from psi.devsonly.utils import filename_to_list
#TODO: there appears to be an issue with QT removing the entries
def update_sys_path():
"""Make sure that the sys path contains all the entries needed
"""
site_packages = get_python_lib()
req = pkg_resources.Requirement.parse('psi.devsonly')
wea = pkg_resources.resource_filename(req, 'windows_easy_install.pth')
ppack_list = filename_to_list(wea)
for p in ppack_list:
full_name = path.join(site_packages, p)
# the lower() is necessary or the entries are not found
if full_name.lower() not in sys.path:
print("adding to the path the entry %s" % full_name)
sys.path.insert(0, full_name)
else:
print("%s already present in the path" % full_name)