The Ignoring Errors docs currently list a way of ignoring a particular error for a particular line:
example = lambda: 'example' # noqa: E731
... and a way of ignoring all errors for an entire file:
# flake8: noqa
from foo import unused
function_that_doesnt_exist()
x = 1+ 2
... and a couple of ways, either through config or through command-line options, of disabling a particular error globally across an entire project.
But what if I want to ignore a particular error across the entirety of a single file - for instance, to disable warnings about unused imports in an __init__.py barrel file that just imports a bunch of classes so that code from other packages can import them from it in turn? The docs don't seem to hint at any syntax for this. Is it possible?
As of Flake8 3.7.0 you can do this using the --per-file-ignores option.
Command line example
flake8 --per-file-ignores="project/__init__.py:F401 setup.py:E121"
Or in your config file
per-file-ignores =
project/__init__.py:F401
setup.py:E121
other_project/*:W9
See the documentation here: http://flake8.pycqa.org/en/latest/user/options.html?highlight=per-file-ignores#cmdoption-flake8-per-file-ignores
It is not possible to place a noqa comment for specific codes at the top of a file like you can for individual lines. # flake8: noqa: F401 may at first appear to work, but it's actually being detected as only # flake8: noqa, which means "ignore all messages in the file".
Before version 3.7.0, ignoring specific errors was only implemented per-line but not per-file.
The feature was discussed in issue #324 and the project chose not to implement. An implementation was proposed in this merge request, which nobody has followed up on.
However, some extensions have emerged to address the problem:
[discontinued] flake8-per-file-ignores lets you ignore specific warning/errors for specific files via an entry in the config.
flake8-putty claims to do the same, but hasn't been updated for a while.
I implemented a flake8 plugin flake8-in-file-ignores to allow adding "ignore" rules in the file itself (as opposed to the built-in config approach), the plugin uses the following syntax
# flake8-in-file-ignores: noqa: E731,E123
Update .flake8 file with
ignore = E123,E125,H404,H405,H803 ... any other rools
Related
I'm currently using isort --profile=black --line-length=79 as a linter in my project for python files.
This produces the Vertical Hanging Indent (mode 3 in isort's documentation kind of output:
from third_party import (
lib1,
lib2,
lib3,
lib4,
)
This multiline mode only applies if the line is longer than 79 characters, though. Is there a mode that cause a multiline output as soon as there are two or more imports on the same line, no matter how long the line is?
I tried hacking it with isort -m=3 --trailing-comma --line-length=1, but shorter line length will cause multiline output even when there is a single import, which I don't want:
from third_party import (
lib1,
)
You should use the --force-grid-wrap 2 flag in the CLI or set in the settings file like pyproject.toml option force_grid_wrap = 2. This would force isort to produce multiline output for 2 or more imports, regardless of line length. More info about this option
How can I instruct Sonarqube to suppress the following warning for a specific python file:
File "foo.py" has 2,345 lines, which is greater than 1,000 authorized. Split it into smaller files.
In the past I've used the # NOSONAR comment to suppress a warning at a specific line, but given that this warning is at the file level instead of the line level, I don't think it would work.
I would prefer to suppress this warning for a specific file instead of suppressing this warning for all files, as this warning is useful in most other circumstances.
I'm not sure how to do it directly with Sonarqube, but in the Jenkins property file I used the following successfully:
# Turn off these rules
sonar.issue.ignore.multicriteria=e1
# python:S104 "Files should not have too many lines of code"
sonar.issue.ignore.multicriteria.e1.ruleKey=python:S104
sonar.issue.ignore.multicriteria.e1.resourceKey=path/to/specific/file.py
To figure out the rulekey needed to be python:S104, I went into my companies code quality portal, where there was a tab on the top called rules. In here, there was a python tab. I scrolled down the list and found an entry called:
Files should not have too many lines of code
Which, incidentally, is not the same warning that a scan of the code base gives.
Clicking on that entry listed python:S104 as the rule key.
I'm using the Sort Imports function of the Python extension for VS Code. I'd like to configure the line length for this to 100; however, I've been unable to properly set this in my settings.json file. From the documentation, it seems like "python.sortImports.args": ["-l", "100"] should work, but it's giving me an error: Invalid patch string: Skipped 1 files.
Any ideas?
There is a known bug with using Sort Imports on __init__.py files. Here is the full solution to put in vscode's .vscode/settings.json:
"python.sortImports.args": ["-ns", "__init__.py", "-l", "100"],
Nowdays, it's adding:
"isort.args": ["-l", "100"],
to your settings file.
This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
What is the best practice for dealing with passwords in github?
How can I track system-specific config files in a repo/project?
Hi,
I would like to hide
DATABASE_NAME = ''
DATABASE_USER = ''
DATABASE_PASSWORD = ''
DATABASE_HOST = ''
Line 13 to 17 of the default Django settings.py file when checking it in github.
I still want to check it in tho, because I am adding modifications from time to time. I just want these four lines to always be set to empty.
You could also have an extra settings file which holds passwords and just import them in your main settings.py
For example:
settings.py
DATABASE_PASSWORD = ''
try:
from dev_settings import *
except ImportError:
pass
dev_settings.py
DATABASE_PASSWORD = 'mypassword'
And keep dev_settings.py out of revision control.
For my configuration files, I create a config.py-example and a config.py. config.py is ignored by the version control. When I deploy, I just copy config.py-example to config.py and update the passwords.
Unfortunately, that's not how Git works - either a file is in version control, or it isn't.
If you don't want the info in Github, then don't check it in. You could keep a copy of the config file in a separate (private) repository elsewhere if you wanted, though.
I would recommend keeping settings.py with those four lines exactly as you've shown them, and have a separate, tiny Python script to add and remove the four bits of secret information (reading them from a file that's not part of your git repository, but rather is safely and secretly kept -- in a couple of copies, for safety -- in very secure places).
You can have a presubmit check to make sure you never, ever push a settings.py that has not been shorn of the secrets (I don't know git enough to tell if it has "presubmit triggers" that can modify the repo, as well as presubmit checks that just check it, but, if it does, then clearly it may be more convenient for you to use said tiny Python script in such a trigger -- indeed, if that's the case, you might want to consider doing the removal/restoring of the secrets by using patch, and a simple diff file to use as its input, so you don't have to write even a line of script for the purpose).
I came across the following header format for Python source files in a document about Python coding guidelines:
#!/usr/bin/env python
"""Foobar.py: Description of what foobar does."""
__author__ = "Barack Obama"
__copyright__ = "Copyright 2009, Planet Earth"
Is this the standard format of headers in the Python world?
What other fields/information can I put in the header?
Python gurus share your guidelines for good Python source headers :-)
Its all metadata for the Foobar module.
The first one is the docstring of the module, that is already explained in Peter's answer.
How do I organize my modules (source files)? (Archive)
The first line of each file shoud be #!/usr/bin/env python. This makes it possible to run the file as a script invoking the interpreter implicitly, e.g. in a CGI context.
Next should be the docstring with a description. If the description is long, the first line should be a short summary that makes sense on its own, separated from the rest by a newline.
All code, including import statements, should follow the docstring. Otherwise, the docstring will not be recognized by the interpreter, and you will not have access to it in interactive sessions (i.e. through obj.__doc__) or when generating documentation with automated tools.
Import built-in modules first, followed by third-party modules, followed by any changes to the path and your own modules. Especially, additions to the path and names of your modules are likely to change rapidly: keeping them in one place makes them easier to find.
Next should be authorship information. This information should follow this format:
__author__ = "Rob Knight, Gavin Huttley, and Peter Maxwell"
__copyright__ = "Copyright 2007, The Cogent Project"
__credits__ = ["Rob Knight", "Peter Maxwell", "Gavin Huttley",
"Matthew Wakefield"]
__license__ = "GPL"
__version__ = "1.0.1"
__maintainer__ = "Rob Knight"
__email__ = "rob#spot.colorado.edu"
__status__ = "Production"
Status should typically be one of "Prototype", "Development", or "Production". __maintainer__ should be the person who will fix bugs and make improvements if imported. __credits__ differs from __author__ in that __credits__ includes people who reported bug fixes, made suggestions, etc. but did not actually write the code.
Here you have more information, listing __author__, __authors__, __contact__, __copyright__, __license__, __deprecated__, __date__ and __version__ as recognized metadata.
I strongly favour minimal file headers, by which I mean just:
#!/usr/bin/env python # [1]
"""\
This script foos the given bars [2]
Usage: myscript.py BAR1 BAR2
"""
import os # standard library, [3]
import sys
import requests # 3rd party packages
import mypackage # local source
[1] The hashbang if, and only if, this file should be able to be directly executed, i.e. run as myscript.py or myscript or maybe even python myscript.py. (The hashbang isn't used in the last case, but providing it gives users the choice of executing it either way.) The hashbang should not be included if the file is a module, intended just to be imported by other Python files.
[2] Module docstring
[3] Imports, grouped in the standard way, ie. three groups of imports, with a single blank line between them. Within each group, imports are sorted. The final group, imports from local source, can either be absolute imports as shown, or explicit relative imports.
Everything else is a waste of time - both for the author and for subsequent maintainers. It wastes the precious visual space at the top of the file with information that is better tracked elsewhere, and is easy to get out of date and become actively misleading.
If you have legal disclaimers or licensing info, it goes into a separate file. It does not need to infect every source code file. Your copyright should be part of this. People should be able to find it in your LICENSE file, not random source code.
Metadata such as authorship and dates is already maintained by your source control. There is no need to add a less-detailed, erroneous, and out-of-date version of the same info in the file itself.
I don't believe there is any other data that everyone needs to put into all their source files. You may have some particular requirement to do so, but such things apply, by definition, only to you. They have no place in “general headers recommended for everyone”.
The answers above are really complete, but if you want a quick and dirty header to copy'n paste, use this:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Module documentation goes here
and here
and ...
"""
Why this is a good one:
The first line is for *nix users. It will choose the Python interpreter in the user path, so will automatically choose the user preferred interpreter.
The second one is the file encoding. Nowadays every file must have a encoding associated. UTF-8 will work everywhere. Just legacy projects would use other encoding.
And a very simple documentation. It can fill multiple lines.
See also: https://www.python.org/dev/peps/pep-0263/
If you just write a class in each file, you don't even need the documentation (it would go inside the class doc).
Also see PEP 263 if you are using a non-ascii characterset
Abstract
This PEP proposes to introduce a syntax to declare the encoding of
a Python source file. The encoding information is then used by the
Python parser to interpret the file using the given encoding. Most
notably this enhances the interpretation of Unicode literals in
the source code and makes it possible to write Unicode literals
using e.g. UTF-8 directly in an Unicode aware editor.
Problem
In Python 2.1, Unicode literals can only be written using the
Latin-1 based encoding "unicode-escape". This makes the
programming environment rather unfriendly to Python users who live
and work in non-Latin-1 locales such as many of the Asian
countries. Programmers can write their 8-bit strings using the
favorite encoding, but are bound to the "unicode-escape" encoding
for Unicode literals.
Proposed Solution
I propose to make the Python source code encoding both visible and
changeable on a per-source file basis by using a special comment
at the top of the file to declare the encoding.
To make Python aware of this encoding declaration a number of
concept changes are necessary with respect to the handling of
Python source code data.
Defining the Encoding
Python will default to ASCII as standard encoding if no other
encoding hints are given.
To define a source code encoding, a magic comment must
be placed into the source files either as first or second
line in the file, such as:
# coding=<encoding name>
or (using formats recognized by popular editors)
#!/usr/bin/python
# -*- coding: <encoding name> -*-
or
#!/usr/bin/python
# vim: set fileencoding=<encoding name> :
...
What I use in some project is this line in the first line for Linux machines:
# -*- coding: utf-8 -*-
As a DOC & Author credit, I like simple string in multiline. Here an example from Example Google Style Python Docstrings
# -*- coding: utf-8 -*-
"""Example Google style docstrings.
This module demonstrates documentation as specified by the `Google Python
Style Guide`_. Docstrings may extend over multiple lines. Sections are created
with a section header and a colon followed by a block of indented text.
Example:
Examples can be given using either the ``Example`` or ``Examples``
sections. Sections support any reStructuredText formatting, including
literal blocks::
$ python example_google.py
Section breaks are created by resuming unindented text. Section breaks
are also implicitly created anytime a new section starts.
Attributes:
module_level_variable1 (int): Module level variables may be documented in
either the ``Attributes`` section of the module docstring, or in an
inline docstring immediately following the variable.
Either form is acceptable, but the two should not be mixed. Choose
one convention to document module level variables and be consistent
with it.
Todo:
* For module TODOs
* You have to also use ``sphinx.ext.todo`` extension
.. _Google Python Style Guide:
http://google.github.io/styleguide/pyguide.html
"""
Also can be nice to add:
"""
#Author: ...
#Date: ....
#Credit: ...
#Links: ...
"""
Additional Formats
Meta-information markup | devguide
"""
:mod:`parrot` -- Dead parrot access
===================================
.. module:: parrot
:platform: Unix, Windows
:synopsis: Analyze and reanimate dead parrots.
.. moduleauthor:: Eric Cleese <eric#python.invalid>
.. moduleauthor:: John Idle <john#python.invalid>
"""
/common-header-python
#!/usr/bin/env python3 Line 1
# -*- coding: utf-8 -*- Line 2
#----------------------------------------------------------------------------
# Created By : name_of_the_creator Line 3
# Created Date: date/month/time ..etc
# version ='1.0'
# ---------------------------------------------------------------------------
Also I report similarly to other answers
__author__ = "Rob Knight, Gavin Huttley, and Peter Maxwell"
__copyright__ = "Copyright 2007, The Cogent Project"
__credits__ = ["Rob Knight", "Peter Maxwell", "Gavin Huttley",
"Matthew Wakefield"]
__license__ = "GPL"
__version__ = "1.0.1"
__maintainer__ = "Rob Knight"
__email__ = "rob#spot.colorado.edu"
__status__ = "Production"