Show all non-critical typing errors as warnings - python

In VSCode's settings.json, I enabled PyLance's type checking:
"python.analysis.typeCheckingMode": "basic"
This shows all typing issues as errors (underlined in red), even when code is valid Python and will run with no issue.
For example, the following code is valid Python, and works:
if 4 % 2 == 0:
a = 3
print(a)
...but PyLance shows an error because of the case where a is unbound:
I want to only mark as "errors" the actual syntax errors that will be rejected by Python, and mark everything else as warnings. I can do it for one category with:
"python.analysis.diagnosticSeverityOverrides": {
"reportGeneralTypeIssues": "warning"
}
How can I do that for all such errors?

Sorry, but I am afraid you only can override the diagnostic severity explicitly one by one.
Such as set "reportUnboundVariable": "warning", to change the error to warning which you have metioned in the above.
But, there is no way to change all of them one time.

Related

Python / Spyder - Undefined variable error, when variable is defined and shown in the environment. Code works even with the error

I am getting a strange error when defining variables in Python 4.1.5 (IDE:Spyder). However, even with the error, the code runs without any issues!
As you can see, the variable social_cost_of_carbon is stored as a variable, but I keep getting that error as show in picture 1 (the error writes: Undefined name 'social_cost_of_carbon' (Pyflakes E)
I feel that the way that i declare those variables might be the reason:
def convert_to_var(df):
desc = []
val = []
for i,row in df.iterrows():
desc.append(i)
val.append(row)
return dict(val)
val_dict = convert_to_var(IA)
locals().update(val_dict)
Since the code runs without any problems, I am not doing anything to resolve this. Do I need to worry and fix this, or do I just let it be and continue without dealing with the error since the code runs smoothly?
Thanking you in advance.
(Spyder maintainer here) As you guessed, the problem is that you're creating your variable dynamically with this line in your code:
locals().update(val_dict)
Since our linter can't find where that variable is properly declared, it reports that it's undefined. But it's safe for you to ignore that message.
Note: For now it's not possible to hide linter warnings. However, in a future version we'll provide a way to do that by adding a comment at the end of a line of the form # noqa.

PEP8 plugin breaks my Type Hint code in Sublime 3

I had to disable the format on save setting, because Python PEP8 Autoformat plugin reformatted my code, causing a syntax error.
My code (focus on last lines):
from typing import List, Tuple
from my_enent import MyEvent
def my_preprocessor(raw_event, context: object, env: MyEnv) \
-> Tuple[dict, VideoFreezeEvent]:
if isinstance(raw_event, dict) and 'Output' in raw_event:
# comments
raw_state_machine_event = json.loads(raw_state_machine_event['Output'])
# comments
parallel_outputs = raw_state_machine_event.get(
'my_data').get('parallel_outputs')
if len(parallel_outputs) > 0:
state_machine_event = parallel_outputs[0]
my_list: List[MyEvent] = [
my_util.populate_dataclass(MyEvent, event)
for event in parallel_outputs
]
another_event = events_list[0]
After the plugin reformats the code, the relevant part of the code that causes the syntax error becomes:
if len(parallel_outputs) > 0:
state_machine_event = parallel_outputs[0]
my_list:
List[MyEvent] = [
my_util.populate_dataclass(MyEvent, event)
for event in parallel_outputs
]
another_event = events_list[0]
How can I prevent/teach the plugin to not break this code please?
Some package settings that might be the way through, if a passage exists in the first place:
{
// list codes for fixes; used by --ignore and --select
"list-fixes": false,
// do not fix these errors / warnings (e.g. [ "E501" , "E4" , "W"])
"ignore": [],
// select errors / warnings (e.g. ["E4", "W"])
"select": [],
// Maximum line length
"max-line-length": 79
}
Your linter sounds like it is rather out of date, as it neither recognizes the walrus operator := or your type annotations. Looking at the plugin's Package Control page, you can see that up at the top it says "MISSING", which means the source code repo is gone, most likely because it's not being maintained anymore. The package was last modified 5 years ago, and there are no recent installations, so there's very strong evidence it's dead.
As a replacement plugin, I'd highly recommend Anaconda
(not related to the Anaconda Python distribution). It works great (mostly), is under active development with frequent updates, bugfixes, and new features, and does code completion and code intelligence along with linting/autoformatting. The website goes through all the configuration you need to do, and how to turn off and on the different features. There are several different linting/formatting options to choose from, including AutoPEP8, PyFlakes, and PyLint. I really like it.
(And no, I'm not associated with it or its author in any way.)
I found workaround. Go to plugin settings (Preferences -> Package Settings -> Python PEP8 Autoformat -> …), add ignore rule, e.g.:
{
// Workaround for typing hints
"ignore": ["E701"],
}
I guess it ignores this warning: https://www.flake8rules.com/rules/E701.html
Seems not very harmful.
I installed Black via pip, and used sublack Sublime plugin, which appears to be running smoothly.
Anaconda Sublime plugin suggested by MattDMo is cool, but a bit slow (with the default settings at least), any my Mac laptop is fairly new.

Python test runner - stestr return codes

Is there any documentation for stestr return codes. I tried to look into https://stestr.readthedocs.io/en/latest/MANUAL.html
but it only talks about non zero return codes but what are the typical return codes, it returns. I am trying to use stestr list
There currently isn't any documentation of the specific returns codes in every error case and honestly the actually value of the exit code is pretty ad-hoc throughout the code base. That being said all the stestr commands will return zero if the command was successful and the value will be greater than zero to indicate an error occurred (which includes a failed test). But adding documentation would be a very welcome addition. You could start by filing an issue about it: https://github.com/mtreinish/stestr/issues/new/choose
The documentation that currently exists that I think you're referring to is about the use of the --subunit flag on several of the commands. That is there because the behavior is different with subunit output enabled. Normally stestr will return an exit code > 0 when there are test failures that occurred during the run. But if you're using the --subunit flag it will always return with 0 even if there are test failures. The only case it will return > 0 is when there was an error generating subunit or another internal error. I wanted to make sure that this difference was clear for users since it might be unexpected.

Why does the default pylintrc have so many disabled messages?

If you run pylint --generate-rcfile > pylintrc and look at the default rc file you'll see the following list of disabled warnings.
Why are they disabled by default?
disable=print-statement,
parameter-unpacking,
unpacking-in-except,
old-raise-syntax,
backtick,
long-suffix,
old-ne-operator,
old-octal-literal,
import-star-module-level,
non-ascii-bytes-literal,
raw-checker-failed,
bad-inline-option,
locally-disabled,
locally-enabled,
file-ignored,
suppressed-message,
useless-suppression,
deprecated-pragma,
apply-builtin,
basestring-builtin,
buffer-builtin,
cmp-builtin,
coerce-builtin,
execfile-builtin,
file-builtin,
long-builtin,
raw_input-builtin,
reduce-builtin,
standarderror-builtin,
unicode-builtin,
xrange-builtin,
coerce-method,
delslice-method,
getslice-method,
setslice-method,
no-absolute-import,
old-division,
dict-iter-method,
dict-view-method,
next-method-called,
metaclass-assignment,
indexing-exception,
raising-string,
reload-builtin,
oct-method,
hex-method,
nonzero-method,
cmp-method,
input-builtin,
round-builtin,
intern-builtin,
unichr-builtin,
map-builtin-not-iterating,
zip-builtin-not-iterating,
range-builtin-not-iterating,
filter-builtin-not-iterating,
using-cmp-argument,
eq-without-hash,
div-method,
idiv-method,
rdiv-method,
exception-message-attribute,
invalid-str-codec,
sys-max-int,
bad-python3-import,
deprecated-string-function,
deprecated-str-translate-call,
deprecated-itertools-function,
deprecated-types-field,
next-method-defined,
dict-items-not-iterating,
dict-keys-not-iterating,
dict-values-not-iterating
From the documentation's Frequently Asked Questions...
Why are there a bunch of messages disabled by default?
pylint does have some messages disabled by default, either because
they are prone to false positives or that they are opinionated enough
for not being included as default messages. But most of the disabled
messages are from the Python 3 porting checker, which is disabled by
default. It needs special activation with the --py3k flag.
I think that such default rc file is designed to apply pylint to python2 code without tons of errors and warnings. Note: most of the disabled statements belongs to python2 syntax and standard library api:
print-statement - print was a statement in Python2, in Python3 it is a function
old-raise-syntax - there was except Exception, e syntax that is invalid for Python3, in Python3 except Exception as e is only valid
xrange-builtin - xrange was replaced with range
etc.
So, with this default rc you can use pylint for python2 code to find out such things as redefined-outer-name, line-too-long and other bad things without getting annoying errors and warnings for valid Python2 syntax and standard library calls.

Stop cssutils from generating warning messages

I am using the parseFile convenience method to read a css file but it is generating a huge amount of warning messages.
I have set validate=False but it is still printing the messages. I have tried to create a CSSParser object and initialising the log object and logging level to none but it is still printing warnings and errors. I looked in the source code and couldn't see where these message are being created so it might be in something that parseFile calls.
Is there any way of stopping the CSSParser.parseFile() from generating message like the ones below?
WARNING CSSStylesheet: Unknown #rule found. [3:43150:#-webkit-keyframes]
WARNING CSSStylesheet: Unknown #rule found. [3:43329: #-moz-keyframes]
WARNING CSSStylesheet: Unknown #rule found. [3:43496: #keyframes]
WARNING CSSStylesheet: Unknown #rule found. [3:43643: #-webkit-keyframes]
WARNING Property: Unknown Property name. [3:79871: min-device-width]
WARNING Property: Unknown Property name. [3:79900: max-device-width]
ERROR MediaQuery: Unexpected syntax, expected "and" but found "(". [3:86572: (]
ERROR MediaQuery: Unexpected syntax, expected "and" but found ":". [3:86582: :]
ERROR MediaQuery: Unexpected syntax. [3:86583: 35em]
ERROR MediaQuery: Unexpected syntax, expected "and" but found ")". [3:86587: )]
Any help would be greatly appreciated!
The logger is a singleton, so, put this line above your instruction
import logging
cssutils.log.setLevel(logging.CRITICAL)
This disables the warning and error logging.

Categories