Usage¶
This library provides the Flake8 plugin flake8-encodings to identify incorrect use of encodings.
Flake8 codes¶
ENC00X: checks for open(), builtins.open and io.open().
Code |
Description |
|---|---|
ENC001 |
no encoding specified for ‘open’. |
ENC002 |
’encoding=None’ used for ‘open’. |
ENC003 |
no encoding specified for ‘open’ with unknown mode. |
ENC004 |
’encoding=None’ used for ‘open’ with unknown mode. |
ENC003 and ENC004 are used in cases where the encoding is omitted (or is explicitly None) but the mode cannot be determined. The file might be opened in binary mode, in which case the encoding argument is ignored, or in text mode, in which case an encoding should be given.
ENC01X: checks for configparser.ConfigParser.read().
Code |
Description |
|---|---|
ENC011 |
no encoding specified for ‘configparser.ConfigParser.read’. |
ENC012 |
’encoding=None’ used for ‘configparser.ConfigParser.read’. |
New in version 0.2.0.
Changed in version 0.4.0: These codes now require the classes extra to be installed 1.
ENC02X: checks for pathlib.Path.open(), read_text() and write_text().
Code |
Description |
|---|---|
ENC021 |
no encoding specified for ‘pathlib.Path.open’. |
ENC022 |
’encoding=None’ used for ‘pathlib.Path.open’. |
ENC023 |
no encoding specified for ‘pathlib.Path.read_text’. |
ENC024 |
’encoding=None’ used for ‘pathlib.Path.read_text’. |
ENC025 |
no encoding specified for ‘pathlib.Path.write_text’. |
ENC026 |
’encoding=None’ used for ‘pathlib.Path.write_text’. |
New in version 0.3.0.
Changed in version 0.4.0: These codes now require the classes extra to be installed 1.
Examples¶
# stdlib
import configparser
open("README.rst").read() # ENC001 no encoding specified for 'open'.
open("README.rst", encoding=None).read() # ENC002 'encoding=None' used for 'open'.
open("README.rst", mode="rb").read() # OK
open("README.rst", mode="rb", encoding=None).read() # OK
def foo(mode: str = 'r'):
open("README.rst", mode=mode).read() # ENC003 no encoding specified for 'open' with unknown mode.
open("README.rst", mode=mode,
encoding=None).read() # ENC004 'encoding=None' used for 'open' with unknown mode.
def load_config(filename: str):
cfg = configparser.ConfigParser()
cfg.read(filename) # ENC011
# cfg.read(filename, encoding=None) # ENC012
def manipulate_file(filename):
path = pathlib.Path(filename)
path.write_text("Hello world") # ENC025
with path.open('a') as fp: # ENC021
f.write("\nHello everyone")
print(path.read_text(encoding=None)) # ENC024
Pre-commit hook¶
flake8-encodings can also be used as a pre-commit hook
See pre-commit for instructions
Sample .pre-commit-config.yaml:
- repo: https://github.com/pycqa/flake8
rev: 3.8.4
hooks:
- id: flake8
additional_dependencies:
- flake8-encodings==0.5.1