Disable linting in Spyder (orange triangles from Pyflakes) - python

I have an import that is only used in a doctest. The linter (Pyflakes) that is used by Spyder to generate warnings right next to the code doesn't like this. I tried a bunch of ways of turning off the "imported but unused" warning, but the orange triangle in the left margin doesn't go away.
Since these triangles do not stem from Pylint but from Pyflakes, options for pylint naturally don't work:
import pandas as pd # pylint: disable=unused-import
import pandas as pd # pylint: disable=W0611
How can I turn the warnings off? I installed Spyder via WinPython.

With the new Spyder version 5.3.3, the following methods are now available in order to suppress the orange warning triangles: Append either # noqa or # analysis:ignore to the end of the line in question.
Suppressing only specific error types does not seem to work at this point in time.
(This information is mostly based on the closing post of the GitHub issue which Ilya mentioned.)

Apparently, this is a known bug in Spyder.
https://github.com/spyder-ide/spyder/issues/7879

Related

Module matplotlib.cm has no [color] member

I've been practicing with matplotlib, then after a short break I opened the codes again and to my surprise, got this error of missing member, which I wasn't getting before.
Module 'matplotlib.cm' has no 'Blues' memberpylint(no-member)
The thing is:
This supposedly missing member is is there, as it shows in the terminal:
Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib.pyplot as plt
>>> plt.cm.Blues
<matplotlib.colors.LinearSegmentedColormap object at 0x000002D00AF42B20>
>>>
It is there. Not missing at all;
plt stands for matplotlib.pyplot, not just matplotlib, as the error suggests.
Here is the script:
import matplotlib.pyplot as plt
from random_walk_mod import RandomWalkMod
print("This program displays a random walk")
# Keep making new walks, as long s the program is active
while True:
# Make a random walk
rw = RandomWalkMod()
rw.fill_walk()
# Plot the points in the walk
plt.style.use('classic')
fig, ax = plt.subplots(figsize=(15,9), dpi=128)
point_numbers = range(rw.num_points)
ax.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues,
edgecolors='none', s=1)
# Emphasize the first and last points
ax.scatter(0,0,c='green', edgecolors='none', s=100)
ax.scatter(rw.x_values[-1],rw.y_values[-1],c='red',edgecolors='none',s=100)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()
keep_running = input("Make another walk? (y/n): ")
if keep_running == 'n':
break
I have found a solution at this forum (https://www.zhihu.com/question/433655496), which is just pass in the color instead of the path, as in:
cmap='Blues'
Instead of:
cmap=plt.cm.Blues
And it works. However, it doesn't seem to wrap it up for me, because I really feel there has to be a workaround to writing the path ("plt.cm.Blues", which a few weeks ago was working fine), because:
plt refers to matplotlib.pylint, NOT just matplotlib. Why is this error pointing at plt (i.e. matplotlib.pyplot) and reporting a missing member from matplotlib.cm (i.e. ignoring pyplot)?
"cm" and its many colors are obviously there. A simple dir search proves it. Actually, both matplotlib and pyplot have an attribute called "cm", which are even the same object:
>>> dir(plt.cm) == dir(matplotlib.cm)
True
So, there are two possible paths for calling "Blues", but VSCode doesn't seem to reach them out. The objects are there and the paths are corectly written, so what is going on?
Not even importing the whole matplotlib solves the problem.
Also, I couldn't find anything related in matplotlib's docs. I hope I'm just very bad at reading docs :)
Any help is much appreciated. Thank you!
[UPDATE: solved]
I had two possible solutions for this, which would be either:
setting up pylint in settings.json so it would ignore the no-member error, or
update Python, which I just had to do.
So I chose the latter, but then VSCode wouldn't recognize the update. No matter what I did (update Python, update VSCode, uninstall and reinstall everything...), VSCode would still not show the updated python interpreter(3.9.5), but instead the old version I had(3.9.1). I set the path correctly, but to VSCode it was like I'd never updated Python.
So after some thorough research, I tried uninstalling VSCode but this time clearing its cache by deleting the folder "Code" (Win+R, then type "%appdata", hit Enter). Finally, VSCode reads the python app as expected, and, even better, the linting problem is gone.
Is it possible that VSCode is using a different python interpreter than your system python that you're using in the terminal? My guess is the VSCode python has a different version of matplotlib that would account for the inconsistency across your two scripts. Your script worked just fine for me on python 3.9.5, with matplotlib 3.4.2
You can run the code, right?
It's a problem with pylint instead of your code.
You can refer to the official docs, explaining the no-member problem in pylint.
And you can add this to the settings.josn file to fix this:
"python.linting.pylintArgs": [
"--c-extension-no-member",
]

qiskit plots not showing up in spyder console

System Informations
Qiskit version: 0.17.0
Python version: 3.7.7
Operating system: Windows 10 home x64
What is the current behavior?
I am using spyder 4.1.1 on Anaconda and any time I try to plot data it does not show up. The code runs with no errors but the plot it self does not appear anywhere.
Steps to reproduce the problem
Running the code listed below which is from the IBMQ website:
import numpy
import qiskit as qc
from qiskit import QuantumCircuit, execute, Aer
import matplotlib
from qiskit.visualization import plot_state_city
circ = qc.QuantumCircuit(3)
circ.h(0)
circ.cx(0,1)
circ.cx(0,2)
print(circ.draw())
backend = Aer.get_backend('statevector_simulator')
job = execute(circ, backend)
result = job.result()
outputstate = result.get_statevector(circ, decimals=3)
print(outputstate)
plot_state_city(outputstate)
What is the expected behavior?
for the plot state city plot to show up in the console or somewhere else
Suggested solutions
I tried using both matplotlib.pylot.show() and matplotlib.pyplot.draw()
Try follow the instructions under "Spyder plots in separate windows" here. Then you can also call circ.draw(output='mpl') to draw the circuit in a window. Hope this helps.
To print your circuit, you have to type print(name of the circuit) so in your case type print(circ).
This may be because the plots don't show in spyder by default. If you run this code in a Jupyter Notebook the plots should show up just fine!
I generally use pycharm ide for running the qiskit code. I think, spyder should also work the same.
Please modify your code as below. I hope, it will work for you.
import numpy
import qiskit as qc
from qiskit import QuantumCircuit, execute, Aer
import matplotlib
from qiskit.visualization import plot_state_city
import matplotlib.pyplot as plt
circ = qc.QuantumCircuit(3)
circ.h(0)
circ.cx(0,1)
circ.cx(0,2)
circ.draw(output='mpl')
backend = Aer.get_backend('statevector_simulator')
job = execute(circ, backend)
result = job.result()
outputstate = result.get_statevector(circ, decimals=3)
print(outputstate)
plot_state_city(outputstate)
plt.show()
1st: I changed the preferences of spyder: Tools ==> Preferences ==> ipython console ==> Graphics ==> Graphics backend ==> Automatic.
2nd: then I have tried the option mentioned in the answer above, with minor modification is that by writing 'mpl' only between the brackets after the word "draw" to have the code be circ.draw('mpl'), and things worked fine.

Ignore warnings in from Python modules (seaborn, sklearn)

There are many questions related to the question title above and all basically tell you to do:
import warnings
warnings.filterwarnings('ignore')
and to make sure this is placed before the first import.
However, even after doing this I get many warnings from seaborn and sklearn. I get UserWarning, DataConversionWarning and RuntimeWarning which, according to documentation, all inherit from Warning and should be covered by the above code.
Is there another way to hide those warnings?
(I cannot really solve most of them anyway)
EDIT
Example 1:
C:\Anaconda3\lib\site-packages\sklearn\preprocessing\data.py:645: DataConversionWarning: Data with input dtype int32, int64 were all converted to float64 by StandardScaler.
return self.partial_fit(X, y)
Example 2
C:\Anaconda3\lib\site-packages\seaborn\distributions.py:340: UserWarning: Attempted to set non-positive bottom ylim on a log-scaled axis.
Invalid limit will be ignored.
ax.set_ylim(0, auto=None)
Example2
It's a bit hard to track down; seaborn imports statsmodels. And in statsmodels/tools/sm_exceptions.py you find this line
warnings.simplefilter('always', category=UserWarning)
in which reverses any previous setting for user warnings.
A solution for now would be to remove that line or to set the warning state after the import of seaborn (and hence statsmodels). In a future version of statsmodels this will be fixed by PR 4712, so using the development version of statsmodels would also be an option.
Example1
I did not find a way to reproduce the first example from sklearn; so that may or may not have a different reason.

Ignore pandas warnings

There are some similar questions, but the replies there do not work for me.
I am trying to do this, as explained in the warnings documentation:
def disable_pandas_warnings():
import warnings
warnings.resetwarnings() # Maybe somebody else is messing with the warnings system?
warnings.filterwarnings('ignore') # Ignore everything
# ignore everything does not work: ignore specific messages, using regex
warnings.filterwarnings('ignore', '.*A value is trying to be set on a copy of a slice from a DataFrame.*')
warnings.filterwarnings('ignore', '.*indexing past lexsort depth may impact performance*')
And I call this at the start of my test/program:
disable_pandas_warnings()
As you can see in the comments, I have:
made sure that the warnings filters are not polluted (since filtering is performed on a first-match way)
ignore all messages
ignore specific messages (by giving message regex)
Nothing seems to work: messages are still displayed. How can I disable all warnings?

python (matplotlib) __NSAutoreleaseNoPool error ... - just leaking

[I originally posted this in serverfault, but was advised there to post it here instead.]
Matplotlib is a python library for data visualization. When I attempt to display a graph on the screen, I get the following error/warnings:
2012-12-21 16:40:05.532 python[9705:903] *** __NSAutoreleaseNoPool(): Object 0x103e25d80 of class NSCFArray autoreleased with no pool in place - just leaking
2012-12-21 16:40:05.534 python[9705:903] *** __NSAutoreleaseNoPool(): Object 0x103e26820 of class __NSFastEnumerationEnumerator autoreleased with no pool in place - just leaking
2012-12-21 16:40:05.535 python[9705:903] *** __NSAutoreleaseNoPool(): Object 0x103e9f080 of class NSObject autoreleased with no pool in place - just leaking
FWIW, one way to produce these results is shown below; all the steps shown (including the call to ipython) are taken from a matplotlib tutorial:
% ipython
...
In [1]: import matplotlib.pyplot as plt
In [2]: plt.plot([1, 3, 2, 4])
Out[3]: [<matplotlib.lines.Line2D at 0x106aabd90>]
In [3]: plt.show()
ALso, FWIW, I've observed exactly the same behavior with multiple styles of installation (on the same machine) of python+numpy+matplotlib+ipython, including installs that use the system-supplied python, those that use the python installed by homebrew, or those that use a python installed directly from source into a location off my home directory.
Any ideas of what may be going on, or what I could do about it?
I am having the same problem, one solution I found is to add the line:
plt.ion()
before the first plotting command. This turns on the interactive plotting mode and the error messages go away. This has only worked for me when plotting on the command line, if I do ion() and then show() in a script the plots don't show up at all, and if I leave the ion() out, I can see my plots, but I get the error messages. This has only happened since updated to version 1.2.0.
It's trying to do something with Cocoa, but Cocoa hasn't really been initialized or anything. You may be able to silence the errors and fix the problems by running this before:
from Foundation import NSAutoreleasePool
pool = NSAutoreleasePool()
And this after:
from AppKit import NSApplication
NSApplication.sharedApplication().run()
This requires PyObjC. Unfortunately, this may only allow for displaying one plot per IPython session. You may wish to try the IPython notebook instead, which removes the dependency on Cocoa.

Categories