Python, disable warnings filter - python

How to disable the filtering of the warnings?
I would like to output several times the same warning, but a filter in the library avoids to output more than once the same warning.
import warnings
for i in range(2):
warnings.warn("warning message")
output:
C:\Users\me\my_script.py:4: UserWarning: warning message
warnings.warn("warning message")
The documentation is here:
https://docs.python.org/2/library/warnings.html
Apparently I have to set "always" in the tuple at the entry of the filter, I don't know how to do so, and where to access this tuple.

You can update warning filters with the warnings.simplefilter() and warnings.filterwarnings() functions; from the module intro:
The determination whether to issue a warning message is controlled by the warning filter, which is a sequence of matching rules and actions. Rules can be added to the filter by calling filterwarnings() and reset to its default state by calling resetwarnings().
To make all warnings repeat beyond the first issue, use
warnings.simplefilter('always')
You can expand on this by adding more details to filter on. For example, your warnings.warn() calls do not specify a category, so the default then is to use warnings.UserWarning; you could add that to the filter:
warnings.simplefilter('always', warnings.UserWarning)
etc. You can use keyword arguments too if you only want to specify some of the filter arguments, such as append=True.

With python 2.7.15rc1, to disable all warnings, I used these two lines of code:
import warnings
warnings.simplefilter("ignore")
I hope it is useful

Related

How does #pytest.mark.filterwarnings work?

According to the docs you can ignore warnings like this:
#pytest.mark.filterwarnings("ignore:api v1")
def test_foo():
which gives:
But there doesn't seem to be any documentation on this mini-language (is it even a minilanguage?)
How is the match done?
I'm asking this because the following test doesn't ignore the DeprecationWarning raised by importing boto3:
#pytest.mark.filterwarnings("ignore:DeprecationWarning")
def test_ignore_warnings():
import boto3
Pytest outputs:
============================================================================================================================== warnings summary ===============================================================================================================================
/home/rob/dev/time-series/.venv/lib/python3.7/site-packages/botocore/awsrequest.py:624
/home/rob/dev/time-series/.venv/lib/python3.7/site-packages/botocore/awsrequest.py:624: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
class HeadersDict(collections.MutableMapping):
-- Docs: https://docs.pytest.org/en/latest/warnings.html
==================================================================================================================== 1 passed, 1 warnings in 0.36 seconds =====================================================================================================================
The filters work the same way as when you use -W argument with python command (see python --help). The format is described in the documentation of the warnings module. In short it's action:message:category:module:line where action is probably mandatory but the other parts can be omitted.
"ignore:api v1" would try to match the message by defining "a string containing a regular expression that the start of the warning message must match". Since you actually want to match category you can skip message. This means that you just seem to be missing one colon after ignore so this is the correct format:
#pytest.mark.filterwarnings("ignore::DeprecationWarning")
def test_ignore_warnings():
import boto3
However, you might apparently still get the warning if it happens during an import of a package outside of a test function. In this case you might need to specify the filter globally as a pytest's argument:
pytest -W "ignore::DeprecationWarning" ./tests/
...or add it to pytest.ini:
[pytest]
filterwarnings =
ignore::DeprecationWarning
If such a global exclusion is undesirable, you can try to limit it to a particular module:
ignore::DeprecationWarning:boto3
Testing
For testing purposes, you can use the following code:
import warnings
def something():
warnings.warn("Test", DeprecationWarning)
#pytest.mark.filterwarnings("ignore::DeprecationWarning")
def test_ignore_warnings():
something()

How to get rid of delays on double_click_input() actions?

Is there a way I can get rid of delays on double_click_input() actions?
What I'm trying to do is double click the edit box and then type keys here. Maybe both of these actions have some delay, so the whole process performing looks very slow.
Code:
myApp = Desktop(backend='uia').window(title_re='myTitle_re')
myApp.window(auto_id='myAutoId').window(title='myTitle').double_click_input()
myApp.descendants(title='myTitle', control_type='Edit')[1].type_keys('myKeys')
And an additional question: I tried to use double_click() here, but it always throws an exception:
AttributeError: WindowSpecification class has no 'double_click'
method.
Then I tried myApp.window(auto_id='myAutoId').window(title='myTitle').wrapper_object().double_click()
And got:
AttributeError: 'ListItemWrapper' object has no attribute
'double_click'
What should I change to get this work?
I'm using pywinauto 0.6.3.
Answering your first question, you can set some timings to null using global settings. For double_click_input:
from pywinauto.timings import Timings
Timings.after_clickinput_wait = 0.0
Timings.after_setcursorpos_wait = 0.0
For real user input (*_input methods) changing timings may cause modified sequence not to work. But you may experiment for your own risk. Sometimes it's better to use silent methods using window messages like WM_CLICK (for "win32" backend) or UIAutomation Patterns like Invoke Pattern (for "uia" backend).
double_click is not implemented for "uia" because it's unclear which UIAutomation Pattern should be interpreted as double click action. We have method .invoke() and ButtonWrapper.click = invoke alias. But for non-buttons InvokePattern may have different meaning. That's why we left it as .invoke().
P.S. Regarding legacy propery text... It can be obtained by .legacy_properties()[u'Value'] for your case (or other value from returned dict). There are methods set_window_text/set_edit_text using ValuePattern so the text can be set silently without any tricks.

'Wildcard' for checking captured log outputs using Python's testfixtures module

I'm writing some unit tests for a server program which catches most exceptions, but logs them, and would like to make assertions on the logged output. I've found the testfixtures package useful to this end; for example:
import logging
import testfixtures
with testfixtures.LogCapture() as l:
logging.info('Here is some info.')
l.check(('root', 'INFO', 'Here is some info.'))
Following the documentation, the check method will raise an error if either the logger name, level, or message is not as expected.
I would like to perform a more 'flexible' kind of test in which I make assertions on the message using a wildcard for the other elements of the tuple. This less stringent assertion would look something like
l.check((*, *, 'Here is some info.'))
but this is not valid syntax. Is there any way to specify a 'wildcard' in the check method of the testfixtures.logcapture.LogCapture class?
The way to check messages only (which, as pointed out to me by the author, is actually described in the documentation) is to use the records attribute of the LogCapture class, which is a list of logging.LogRecord objects. So the appropriate assertion is:
assert l.records[-1].getMessage() == 'Here is some info.'

How to disable Python RQ job's SyntaxWarning?

Trying to avoid having RQ display a warning message (to console) about using the meta dictionary for arbitrary property usage. We are using it as is specified, and the warning continues to display.
The warning displayed is as follows:
/usr/local/lib/python2.7/site-packages/rq/job.py:381: SyntaxWarning: Getting custom properties from the job instance directly will be unsupported as of RQ 0.4. Please use the meta dict to store all custom variables. So instead of this:
job.foo
Use this:
job.meta['foo']
SyntaxWarning)
Basically, it is pretty annoying because it interferes with normal debugging activities.
Any ideas on how to disable this?
Use the built-in warnings module's simplefilter method. Requires use of a context manager. Code example copied wholesale from the linked section:
import warnings
def fxn():
warnings.warn("deprecated", DeprecationWarning)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
fxn()
Further arguments to simplefilter allow you to filter just the warnings you're getting from the specific place in the code you know about-- probably a good idea so other, new warnings that arise later won't be obscured.

Pylint best practices

Pylint looks like a good tool for running analysis of Python code.
However, our main objective is to catch any potential bugs and not coding conventions. Enabling all Pylint checks seems to generate a lot of noise. What is the set of Pylint features you use and is effective?
You can block any warnings/errors you don't like, via:
pylint --disable=error1,error2
I've blocked the following (description from http://www.logilab.org/card/pylintfeatures):
W0511: Used when a warning note as FIXME or XXX is detected
W0142: Used * or * magic*. Used when a function or method is called using *args or **kwargs to dispatch arguments. This doesn't improve readability and should be used with care.
W0141: Used builtin function %r. Used when a black listed builtin function is used (see the bad-function option). Usual black listed functions are the ones like map, or filter, where Python offers now some cleaner alternative like list comprehension.
R0912: Too many branches (%s/%s). Used when a function or method has too many branches, making it hard to follow.
R0913: Too many arguments (%s/%s). Used when a function or method takes too many arguments.
R0914: Too many local variables (%s/%s). Used when a function or method has too many local variables.
R0903: Too few public methods (%s/%s). Used when class has too few public methods, so be sure it's really worth it.
W0212: Access to a protected member %s of a client class. Used when a protected member (i.e. class member with a name beginning with an underscore) is access outside the class or a descendant of the class where it's defined.
W0312: Found indentation with %ss instead of %ss. Used when there are some mixed tabs and spaces in a module.
C0111: Missing docstring. Used when a module, function, class or method has no docstring. Some special methods like __init__ don't necessarily require a docstring.
C0103: Invalid name "%s" (should match %s). Used when the name doesn't match the regular expression associated to its type (constant, variable, class...).
To persistently disable warnings and conventions:
Create a ~/.pylintrc file by running pylint --generate-rcfile > ~/.pylintrc
Edit ~/.pylintrc
Uncomment disable= and change that line to disable=W,C
Pyflakes should serve your purpose well.
-E will only flag what Pylint thinks is an error (i.e., no warnings, no conventions, etc.)
Using grep like:
pylint my_file.py | grep -v "^C"
Edit :
As mentionned in the question, to remove the conventions advices from pylint output, you remove the lines that start with an uppercase C.
From the doc of pylint, the output consists in lines that fit the format
MESSAGE_TYPE: LINE_NUM:[OBJECT:] MESSAGE
and the message type can be:
[R]efactor for a “good practice” metric violation
[C]onvention for coding standard violation
[W]arning for stylistic problems, or minor programming issues
[E]rror for important programming issues (i.e. most probably bug)
[F]atal for errors which prevented further processing
Only the first letter is displayed, so you can play with grep to select/remove the level of message type you want.
I didn't use Pylint recently, but I would probably use a parameter inside Pylint to do so.

Categories