From 41f34fb17553a7242a32537b2738de179a747b51 Mon Sep 17 00:00:00 2001 From: Trevor James Smith <10819524+Zeitsperre@users.noreply.github.com> Date: Thu, 18 Jan 2024 14:53:41 -0500 Subject: [PATCH] configure pylint with toml support, address some small errors --- .pre-commit-config.yaml | 5 +- pylintrc => .pylintrc.toml | 799 ++++++++++++++++-------------------- xclim/cli.py | 6 +- xclim/core/calendar.py | 36 +- xclim/core/indicator.py | 6 +- xclim/core/options.py | 2 +- xclim/core/units.py | 4 +- xclim/core/utils.py | 7 +- xclim/ensembles/_filters.py | 2 +- xclim/sdba/processing.py | 8 +- xclim/sdba/properties.py | 2 +- xclim/testing/utils.py | 7 +- 12 files changed, 400 insertions(+), 484 deletions(-) rename pylintrc => .pylintrc.toml (56%) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e219da850..898b68aa9 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -27,9 +27,10 @@ repos: hooks: - id: toml-sort-fix - repo: https://github.com/pylint-dev/pylint - rev: v2.17.2 + rev: v3.0.3 hooks: - id: pylint + args: [ '--rcfile=.pylintrc.toml' ] - repo: https://github.com/adrienverge/yamllint.git rev: v1.33.0 hooks: @@ -44,7 +45,7 @@ repos: hooks: - id: isort - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.1.11 + rev: v0.1.13 hooks: - id: ruff - repo: https://github.com/pycqa/flake8 diff --git a/pylintrc b/.pylintrc.toml similarity index 56% rename from pylintrc rename to .pylintrc.toml index cdac8c797..a51464284 100644 --- a/pylintrc +++ b/.pylintrc.toml @@ -1,642 +1,553 @@ -[MAIN] +[tool.pylint.main] +# Analyse import fallback blocks. This can be used to support both Python 2 and 3 +# compatible code, which means that the block might have code that exists only in +# one or another interpreter, leading to false positives when analysed. +# analyse-fallback-blocks = -# Analyse import fallback blocks. This can be used to support both Python 2 and -# 3 compatible code, which means that the block might have code that exists -# only in one or another interpreter, leading to false positives when analysed. -analyse-fallback-blocks=no +# Clear in-memory caches upon conclusion of linting. Useful if running pylint in +# a server-like mode. +# clear-cache-post-run = -# Load and enable all available extensions. Use --list-extensions to see a list -# all available extensions. -#enable-all-extensions= - -# In error mode, messages with a category besides ERROR or FATAL are -# suppressed, and no reports are done by default. Error mode is compatible with -# disabling specific errors. -#errors-only= - -# Always return a 0 (non-error) status code, even if lint errors are found. -# This is primarily useful in continuous integration scripts. -#exit-zero= +# Always return a 0 (non-error) status code, even if lint errors are found. This +# is primarily useful in continuous integration scripts. +exit-zero = false # A comma-separated list of package or module names from where C extensions may # be loaded. Extensions are loading into the active Python interpreter and may # run arbitrary code. -extension-pkg-allow-list= +# extension-pkg-allow-list = # A comma-separated list of package or module names from where C extensions may # be loaded. Extensions are loading into the active Python interpreter and may # run arbitrary code. (This is an alternative name to extension-pkg-allow-list # for backward compatibility.) -extension-pkg-whitelist= +# extension-pkg-whitelist = # Return non-zero exit code if any of these messages/categories are detected, # even if score is above --fail-under value. Syntax same as enable. Messages # specified are enabled, while categories only check already-enabled messages. -fail-on= +# fail-on = # Specify a score threshold under which the program will exit with error. -fail-under=10 +fail-under = 10 # Interpret the stdin as a python script, whose filename needs to be passed as # the module_or_package argument. -#from-stdin= +# from-stdin = # Files or directories to be skipped. They should be base names, not paths. -ignore= +ignore = ["CVS"] # Add files or directories matching the regular expressions patterns to the # ignore-list. The regex matches against paths and can be in Posix or Windows -# format. Because '\' represents the directory delimiter on Windows systems, it +# format. Because '\\' represents the directory delimiter on Windows systems, it # can't be used as an escape character. -ignore-paths= - docs, - xclim/testing/tests, +# ignore-paths = -# Files or directories matching the regular expression patterns are skipped. -# The regex matches against base names, not paths. The default value ignores -# Emacs file locks -ignore-patterns=^\.# +# Files or directories matching the regular expression patterns are skipped. The +# regex matches against base names, not paths. The default value ignores Emacs +# file locks +ignore-patterns = ["^\\.#"] -# List of module names for which member attributes should not be checked -# (useful for modules/projects where namespaces are manipulated during runtime -# and thus existing member attributes cannot be deduced by static analysis). It -# supports qualified module names, as well as Unix pattern matching. -ignored-modules= +# List of module names for which member attributes should not be checked (useful +# for modules/projects where namespaces are manipulated during runtime and thus +# existing member attributes cannot be deduced by static analysis). It supports +# qualified module names, as well as Unix pattern matching. +# ignored-modules = # Python code to execute, usually for sys.path manipulation such as # pygtk.require(). -#init-hook= +# init-hook = # Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the # number of processors available to use, and will cap the count on Windows to # avoid hangs. -jobs=0 +jobs = 1 -# Control the amount of potential inferred values when inferring a single -# object. This can help the performance when dealing with large functions or -# complex, nested conditions. -limit-inference-results=100 +# Control the amount of potential inferred values when inferring a single object. +# This can help the performance when dealing with large functions or complex, +# nested conditions. +limit-inference-results = 100 # List of plugins (as comma separated values of python module names) to load, # usually to register additional checkers. -load-plugins= +# load-plugins = # Pickle collected data for later comparisons. -persistent=yes +persistent = true -# Minimum Python version to use for version dependent checks. Will default to -# the version used to run pylint. -py-version=3.8 +# Minimum Python version to use for version dependent checks. Will default to the +# version used to run pylint. +py-version = "3.8" # Discover python modules and packages in the file system subtree. -recursive=no +# recursive = + +# Add paths to the list of the source roots. Supports globbing patterns. The +# source root is an absolute path or a path relative to the current working +# directory used to determine a package namespace for modules located under the +# source root. +# source-roots = # When enabled, pylint would attempt to guess common misconfiguration and emit # user-friendly hints instead of false-positive error messages. -suggestion-mode=yes +suggestion-mode = true # Allow loading of arbitrary C extensions. Extensions are imported into the # active Python interpreter and may run arbitrary code. -unsafe-load-any-extension=no - -# In verbose mode, extra non-checker-related info will be displayed. -#verbose= - - -[REPORTS] - -# Python expression which should return a score less than or equal to 10. You -# have access to the variables 'fatal', 'error', 'warning', 'refactor', -# 'convention', and 'info' which contain the number of messages in each -# category, as well as 'statement' which is the total number of statements -# analyzed. This score is used by the global evaluation report (RP0004). -evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)) - -# Template used to display messages. This is a python new-style format string -# used to format the message information. See doc for all details. -msg-template= - -# Set the output format. Available formats are text, parseable, colorized, json -# and msvs (visual studio). You can also give a reporter class, e.g. -# mypackage.mymodule.MyReporterClass. -#output-format= - -# Tells whether to display a full report or only the messages. -reports=no - -# Activate the evaluation score. -score=yes - - -[MESSAGES CONTROL] - -# Only show warnings with the listed confidence levels. Leave empty to show -# all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE, -# UNDEFINED. -confidence=HIGH, - CONTROL_FLOW, - INFERENCE, - INFERENCE_FAILURE, - UNDEFINED - -# Disable the message, report, category or checker with the given id(s). You -# can either give multiple identifiers separated by comma (,) or put this -# option multiple times (only on the command line, not in the configuration -# file where it should appear only once). You can also use "--disable=all" to -# disable everything first and then re-enable specific checks. For example, if -# you want to run only the similarities checker, you can use "--disable=all -# --enable=similarities". If you want to run only the classes checker, but have -# no Warning level messages displayed, use "--disable=all --enable=classes -# --disable=W". -disable=arguments-differ, - arguments-out-of-order, - bad-inline-option, - deprecated-pragma, - file-ignored, - invalid-name, - invalid-unary-operand-type, - line-too-long, - locally-disabled, - missing-function-docstring, - missing-module-docstring, - non-ascii-name, - pointless-string-statement, - protected-access, - raw-checker-failed, - suppressed-message, - too-few-public-methods, - too-many-arguments, - too-many-branches, - too-many-lines, - too-many-locals, - too-many-nested-blocks, - too-many-statements, - unspecified-encoding, - unused-argument, - use-symbolic-message-instead, - useless-suppression, - wrong-import-order, - - -# Enable the message, report, category or checker with the given id(s). You can -# either give multiple identifier separated by comma (,) or put this option -# multiple time (only on the command line, not in the configuration file where -# it should appear only once). See also the "--disable" option for examples. -enable=c-extension-no-member - - -[METHOD_ARGS] - -# List of qualified names (i.e., library.method) which require a timeout -# parameter e.g. 'requests.api.get,requests.api.post' -timeout-methods=requests.api.delete,requests.api.get,requests.api.head,requests.api.options,requests.api.patch,requests.api.post,requests.api.put,requests.api.request - - -[EXCEPTIONS] - -# Exceptions that will emit a warning when caught. -overgeneral-exceptions=builtins.BaseException, - builtins.Exception - - -[REFACTORING] - -# Maximum number of nested blocks for function / method body -max-nested-blocks=5 - -# Complete name of functions that never returns. When checking for -# inconsistent-return-statements if a never returning function is called then -# it will be considered as an explicit return statement and no message will be -# printed. -never-returning-functions=sys.exit,argparse.parse_error - - -[DESIGN] - -# List of regular expressions of class ancestor names to ignore when counting -# public methods (see R0903) -exclude-too-few-public-methods= - -# List of qualified class names to ignore when counting class parents (see -# R0901) -ignored-parents= - -# Maximum number of arguments for function / method. -max-args=5 - -# Maximum number of attributes for a class (see R0902). -max-attributes=7 - -# Maximum number of boolean expressions in an if statement (see R0916). -max-bool-expr=5 - -# Maximum number of branch for function / method body. -max-branches=12 - -# Maximum number of locals for function / method body. -max-locals=15 - -# Maximum number of parents for a class (see R0901). -max-parents=7 - -# Maximum number of public methods for a class (see R0904). -max-public-methods=20 - -# Maximum number of return / yield for function / method body. -max-returns=6 - -# Maximum number of statements in function / method body. -max-statements=50 - -# Minimum number of public methods for a class (see R0903). -min-public-methods=2 - - -[IMPORTS] - -# List of modules that can be imported at any level, not just the top level -# one. -allow-any-import-level= - -# Allow wildcard imports from modules that define __all__. -allow-wildcard-with-all=yes - -# Deprecated modules which should not be used, separated by a comma. -deprecated-modules= - -# Output a graph (.gv or any supported image format) of external dependencies -# to the given file (report RP0402 must not be disabled). -ext-import-graph= - -# Output a graph (.gv or any supported image format) of all (i.e. internal and -# external) dependencies to the given file (report RP0402 must not be -# disabled). -import-graph= - -# Output a graph (.gv or any supported image format) of internal dependencies -# to the given file (report RP0402 must not be disabled). -int-import-graph= - -# Force import order to recognize a module as part of the standard -# compatibility libraries. -known-standard-library= - -# Force import order to recognize a module as part of a third party library. -known-third-party=enchant - -# Couples of modules and preferred modules, separated by a comma. -preferred-modules= - - -[CLASSES] - -# Warn about protected attribute access inside special methods -check-protected-access-in-special-methods=no - -# List of method names used to declare (i.e. assign) instance attributes. -defining-attr-methods=__init__, - __new__, - setUp, - __post_init__ - -# List of member names, which should be excluded from the protected access -# warning. -exclude-protected=_asdict, - _fields, - _replace, - _source, - _make - -# List of valid names for the first argument in a class method. -valid-classmethod-first-arg=cls - -# List of valid names for the first argument in a metaclass class method. -valid-metaclass-classmethod-first-arg=cls - - -[BASIC] +# unsafe-load-any-extension = +[tool.pylint.basic] # Naming style matching correct argument names. -argument-naming-style=snake_case +argument-naming-style = "snake_case" -# Regular expression matching correct argument names. Overrides argument- -# naming-style. If left empty, argument names will be checked with the set -# naming style. -#argument-rgx= +# Regular expression matching correct argument names. Overrides argument-naming- +# style. If left empty, argument names will be checked with the set naming style. +# argument-rgx = # Naming style matching correct attribute names. -attr-naming-style=snake_case +attr-naming-style = "snake_case" # Regular expression matching correct attribute names. Overrides attr-naming- # style. If left empty, attribute names will be checked with the set naming # style. -#attr-rgx= +# attr-rgx = # Bad variable names which should always be refused, separated by a comma. -bad-names=foo, - bar, - baz, - toto, - tutu, - tata +bad-names = ["foo", "bar", "baz", "toto", "tutu", "tata"] # Bad variable names regexes, separated by a comma. If names match any regex, # they will always be refused -bad-names-rgxs= +# bad-names-rgxs = # Naming style matching correct class attribute names. -class-attribute-naming-style=any +class-attribute-naming-style = "any" # Regular expression matching correct class attribute names. Overrides class- # attribute-naming-style. If left empty, class attribute names will be checked # with the set naming style. -#class-attribute-rgx= +# class-attribute-rgx = # Naming style matching correct class constant names. -class-const-naming-style=UPPER_CASE +class-const-naming-style = "UPPER_CASE" # Regular expression matching correct class constant names. Overrides class- # const-naming-style. If left empty, class constant names will be checked with # the set naming style. -#class-const-rgx= +# class-const-rgx = # Naming style matching correct class names. -class-naming-style=PascalCase +class-naming-style = "PascalCase" -# Regular expression matching correct class names. Overrides class-naming- -# style. If left empty, class names will be checked with the set naming style. -#class-rgx= +# Regular expression matching correct class names. Overrides class-naming-style. +# If left empty, class names will be checked with the set naming style. +# class-rgx = # Naming style matching correct constant names. -const-naming-style=UPPER_CASE +const-naming-style = "UPPER_CASE" # Regular expression matching correct constant names. Overrides const-naming- -# style. If left empty, constant names will be checked with the set naming -# style. -#const-rgx= +# style. If left empty, constant names will be checked with the set naming style. +# const-rgx = -# Minimum line length for functions/classes that require docstrings, shorter -# ones are exempt. -docstring-min-length=-1 +# Minimum line length for functions/classes that require docstrings, shorter ones +# are exempt. +docstring-min-length = -1 # Naming style matching correct function names. -function-naming-style=snake_case +function-naming-style = "snake_case" -# Regular expression matching correct function names. Overrides function- -# naming-style. If left empty, function names will be checked with the set -# naming style. -#function-rgx= +# Regular expression matching correct function names. Overrides function-naming- +# style. If left empty, function names will be checked with the set naming style. +# function-rgx = # Good variable names which should always be accepted, separated by a comma. -good-names=i, - j, - k, - _, - da, - ds, - +good-names = ["i", "j", "k", "ex", "Run", "_"] # Good variable names regexes, separated by a comma. If names match any regex, # they will always be accepted -good-names-rgxs= +# good-names-rgxs = # Include a hint for the correct naming format with invalid-name. -include-naming-hint=no +# include-naming-hint = # Naming style matching correct inline iteration names. -inlinevar-naming-style=any +inlinevar-naming-style = "any" # Regular expression matching correct inline iteration names. Overrides # inlinevar-naming-style. If left empty, inline iteration names will be checked # with the set naming style. -#inlinevar-rgx= +# inlinevar-rgx = # Naming style matching correct method names. -method-naming-style=snake_case +method-naming-style = "snake_case" # Regular expression matching correct method names. Overrides method-naming- # style. If left empty, method names will be checked with the set naming style. -#method-rgx= +# method-rgx = # Naming style matching correct module names. -module-naming-style=snake_case +module-naming-style = "snake_case" # Regular expression matching correct module names. Overrides module-naming- # style. If left empty, module names will be checked with the set naming style. -#module-rgx= +# module-rgx = -# Colon-delimited sets of names that determine each other's naming style when -# the name regexes allow several styles. -name-group= +# Colon-delimited sets of names that determine each other's naming style when the +# name regexes allow several styles. +# name-group = -# Regular expression which should only match function or class names that do -# not require a docstring. -no-docstring-rgx=^_ +# Regular expression which should only match function or class names that do not +# require a docstring. +no-docstring-rgx = "^_" # List of decorators that produce properties, such as abc.abstractproperty. Add -# to this list to register other decorators that produce valid properties. -# These decorators are taken in consideration only for invalid-name. -property-classes=abc.abstractproperty +# to this list to register other decorators that produce valid properties. These +# decorators are taken in consideration only for invalid-name. +property-classes = ["abc.abstractproperty"] + +# Regular expression matching correct type alias names. If left empty, type alias +# names will be checked with the set naming style. +# typealias-rgx = # Regular expression matching correct type variable names. If left empty, type # variable names will be checked with the set naming style. -#typevar-rgx= +# typevar-rgx = # Naming style matching correct variable names. -variable-naming-style=snake_case +variable-naming-style = "snake_case" -# Regular expression matching correct variable names. Overrides variable- -# naming-style. If left empty, variable names will be checked with the set -# naming style. -#variable-rgx= +# Regular expression matching correct variable names. Overrides variable-naming- +# style. If left empty, variable names will be checked with the set naming style. +# variable-rgx = +[tool.pylint.classes] +# Warn about protected attribute access inside special methods +# check-protected-access-in-special-methods = -[SIMILARITIES] - -# Comments are removed from the similarity computation -ignore-comments=yes +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods = ["__init__", "__new__", "setUp", "asyncSetUp", "__post_init__"] -# Docstrings are removed from the similarity computation -ignore-docstrings=yes +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected = ["_asdict", "_fields", "_replace", "_source", "_make", "os._exit"] -# Imports are removed from the similarity computation -ignore-imports=yes +# List of valid names for the first argument in a class method. +valid-classmethod-first-arg = ["cls"] -# Signatures are removed from the similarity computation -ignore-signatures=yes +# List of valid names for the first argument in a metaclass class method. +valid-metaclass-classmethod-first-arg = ["mcs"] -# Minimum lines number of a similarity. -min-similarity-lines=4 +[tool.pylint.design] +# List of regular expressions of class ancestor names to ignore when counting +# public methods (see R0903) +# exclude-too-few-public-methods = +# List of qualified class names to ignore when counting class parents (see R0901) +# ignored-parents = -[LOGGING] +# Maximum number of arguments for function / method. +max-args = 15 -# The type of string formatting that logging methods do. `old` means using % -# formatting, `new` is for `{}` formatting. -logging-format-style=old +# Maximum number of attributes for a class (see R0902). +max-attributes = 7 -# Logging modules to check that the string format arguments are in logging -# function parameter format. -logging-modules=logging +# Maximum number of boolean expressions in an if statement (see R0916). +max-bool-expr = 5 +# Maximum number of branch for function / method body. +max-branches = 30 -[VARIABLES] +# Maximum number of locals for function / method body. +max-locals = 50 -# List of additional names supposed to be defined in builtins. Remember that -# you should avoid defining new builtins when possible. -additional-builtins= +# Maximum number of parents for a class (see R0901). +max-parents = 7 -# Tells whether unused global variables should be treated as a violation. -allow-global-unused-variables=yes +# Maximum number of public methods for a class (see R0904). +max-public-methods = 20 -# List of names allowed to shadow builtins -allowed-redefined-builtins= +# Maximum number of return / yield for function / method body. +max-returns = 13 -# List of strings which can identify a callback function by name. A callback -# name must start or end with one of those strings. -callbacks=cb_, - _cb +# Maximum number of statements in function / method body. +max-statements = 100 -# A regular expression matching the name of dummy variables (i.e. expected to -# not be used). -dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ +# Minimum number of public methods for a class (see R0903). +min-public-methods = 2 -# Argument names that match this expression will be ignored. -ignored-argument-names=_.*|^ignored_|^unused_ +[tool.pylint.exceptions] +# Exceptions that will emit a warning when caught. +overgeneral-exceptions = ["builtins.BaseException", "builtins.Exception"] -# Tells whether we should check for unused import in __init__ files. -init-import=no +[tool.pylint.format] +# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. +# expected-line-ending-format = -# List of qualified module names which can have objects that can redefine -# builtins. -redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io +# Regexp for a line that is allowed to be longer than the limit. +ignore-long-lines = "^\\s*(# )??$" +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren = 4 -[SPELLING] +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string = " " -# Limits count of emitted suggestions for spelling mistakes. -max-spelling-suggestions=4 +# Maximum number of characters on a single line. +max-line-length = 150 -# Spelling dictionary name. Available dictionaries: en (aspell), en_AU -# (aspell), en_CA (aspell), en_GB (aspell), en_US (aspell). -spelling-dict= +# Maximum number of lines in a module. +max-module-lines = 1000 -# List of comma separated words that should be considered directives if they -# appear at the beginning of a comment and should not be checked. -spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy: +# Allow the body of a class to be on the same line as the declaration if body +# contains single statement. +# single-line-class-stmt = -# List of comma separated words that should not be checked. -spelling-ignore-words= +# Allow the body of an if to be on the same line as the test if there is no else. +# single-line-if-stmt = -# A path to a file that contains the private dictionary; one word per line. -spelling-private-dict-file= +[tool.pylint.imports] +# List of modules that can be imported at any level, not just the top level one. +# allow-any-import-level = -# Tells whether to store unknown words to the private dictionary (see the -# --spelling-private-dict-file option) instead of raising a message. -spelling-store-unknown-words=no +# Allow explicit reexports by alias from a package __init__. +# allow-reexport-from-package = +# Allow wildcard imports from modules that define __all__. +# allow-wildcard-with-all = -[FORMAT] +# Deprecated modules which should not be used, separated by a comma. +# deprecated-modules = -# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. -expected-line-ending-format= +# Output a graph (.gv or any supported image format) of external dependencies to +# the given file (report RP0402 must not be disabled). +# ext-import-graph = -# Regexp for a line that is allowed to be longer than the limit. -ignore-long-lines=^\s*(# )??$ +# Output a graph (.gv or any supported image format) of all (i.e. internal and +# external) dependencies to the given file (report RP0402 must not be disabled). +# import-graph = -# Number of spaces of indent required inside a hanging or continued line. -indent-after-paren=4 +# Output a graph (.gv or any supported image format) of internal dependencies to +# the given file (report RP0402 must not be disabled). +# int-import-graph = -# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 -# tab). -indent-string=' ' +# Force import order to recognize a module as part of the standard compatibility +# libraries. +# known-standard-library = -# Maximum number of characters on a single line. -max-line-length=100 +# Force import order to recognize a module as part of a third party library. +known-third-party = ["enchant"] -# Maximum number of lines in a module. -max-module-lines=1000 +# Couples of modules and preferred modules, separated by a comma. +# preferred-modules = -# Allow the body of a class to be on the same line as the declaration if body -# contains single statement. -single-line-class-stmt=no +[tool.pylint.logging] +# The type of string formatting that logging methods do. `old` means using % +# formatting, `new` is for `{}` formatting. +logging-format-style = "old" -# Allow the body of an if to be on the same line as the test if there is no -# else. -single-line-if-stmt=no +# Logging modules to check that the string format arguments are in logging +# function parameter format. +logging-modules = ["logging"] + +[tool.pylint."messages control"] +# Only show warnings with the listed confidence levels. Leave empty to show all. +# Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE, UNDEFINED. +confidence = ["HIGH", "CONTROL_FLOW", "INFERENCE", "INFERENCE_FAILURE", "UNDEFINED"] + +# Disable the message, report, category or checker with the given id(s). You can +# either give multiple identifiers separated by comma (,) or put this option +# multiple times (only on the command line, not in the configuration file where +# it should appear only once). You can also use "--disable=all" to disable +# everything first and then re-enable specific checks. For example, if you want +# to run only the similarities checker, you can use "--disable=all +# --enable=similarities". If you want to run only the classes checker, but have +# no Warning level messages displayed, use "--disable=all --enable=classes +# --disable=W". +disable = [ + "arguments-differ", + "bad-inline-option", + "deprecated-pragma", + "file-ignored", + "invalid-name", + "invalid-unary-operand-type", + "locally-disabled", + "missing-module-docstring", + "protected-access", + "raw-checker-failed", + "redefined-outer-name", + "superfluous-parens", + "suppressed-message", + "unused-argument", + "use-symbolic-message-instead", + "useless-suppression" +] +# Enable the message, report, category or checker with the given id(s). You can +# either give multiple identifier separated by comma (,) or put this option +# multiple time (only on the command line, not in the configuration file where it +# should appear only once). See also the "--disable" option for examples. +enable = ["c-extension-no-member"] -[MISCELLANEOUS] +[tool.pylint.method_args] +# List of qualified names (i.e., library.method) which require a timeout +# parameter e.g. 'requests.api.get,requests.api.post' +timeout-methods = ["requests.api.delete", "requests.api.get", "requests.api.head", "requests.api.options", "requests.api.patch", "requests.api.post", "requests.api.put", "requests.api.request"] +[tool.pylint.miscellaneous] # List of note tags to take in consideration, separated by a comma. -notes=FIXME, - XXX, - TODO +notes = ["FIXME", "XXX", "TODO"] # Regular expression of note tags to take in consideration. -notes-rgx= +# notes-rgx = + +[tool.pylint.refactoring] +# Maximum number of nested blocks for function / method body +max-nested-blocks = 10 + +# Complete name of functions that never returns. When checking for inconsistent- +# return-statements if a never returning function is called then it will be +# considered as an explicit return statement and no message will be printed. +never-returning-functions = ["sys.exit", "argparse.parse_error"] + +[tool.pylint.reports] +# Python expression which should return a score less than or equal to 10. You +# have access to the variables 'fatal', 'error', 'warning', 'refactor', +# 'convention', and 'info' which contain the number of messages in each category, +# as well as 'statement' which is the total number of statements analyzed. This +# score is used by the global evaluation report (RP0004). +evaluation = "max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10))" + +# Template used to display messages. This is a python new-style format string +# used to format the message information. See doc for all details. +# msg-template = + +# Set the output format. Available formats are text, parseable, colorized, json +# and msvs (visual studio). You can also give a reporter class, e.g. +# mypackage.mymodule.MyReporterClass. +# output-format = + +# Tells whether to display a full report or only the messages. +# reports = + +# Activate the evaluation score. +score = true + +[tool.pylint.similarities] +# Comments are removed from the similarity computation +ignore-comments = true + +# Docstrings are removed from the similarity computation +ignore-docstrings = true + +# Imports are removed from the similarity computation +ignore-imports = true + +# Signatures are removed from the similarity computation +ignore-signatures = true + +# Minimum lines number of a similarity. +min-similarity-lines = 10 + +[tool.pylint.spelling] +# Limits count of emitted suggestions for spelling mistakes. +max-spelling-suggestions = 4 + +# Spelling dictionary name. No available dictionaries : You need to install both +# the python package and the system dependency for enchant to work.. +# spelling-dict = + +# List of comma separated words that should be considered directives if they +# appear at the beginning of a comment and should not be checked. +spelling-ignore-comment-directives = "fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy:" + +# List of comma separated words that should not be checked. +# spelling-ignore-words = +# A path to a file that contains the private dictionary; one word per line. +# spelling-private-dict-file = -[TYPECHECK] +# Tells whether to store unknown words to the private dictionary (see the +# --spelling-private-dict-file option) instead of raising a message. +# spelling-store-unknown-words = +[tool.pylint.typecheck] # List of decorators that produce context managers, such as # contextlib.contextmanager. Add to this list to register other decorators that # produce valid context managers. -contextmanager-decorators=contextlib.contextmanager +contextmanager-decorators = ["contextlib.contextmanager"] # List of members which are set dynamically and missed by pylint inference # system, and so shouldn't trigger E1101 when accessed. Python regular # expressions are accepted. -generated-members= +# generated-members = -# Tells whether to warn about missing members when the owner of the attribute -# is inferred to be None. -ignore-none=yes +# Tells whether missing members accessed in mixin class should be ignored. A +# class is considered mixin if its name matches the mixin-class-rgx option. +# Tells whether to warn about missing members when the owner of the attribute is +# inferred to be None. +ignore-none = true # This flag controls whether pylint should warn about no-member and similar -# checks whenever an opaque object is returned when inferring. The inference -# can return multiple potential results while evaluating a Python object, but -# some branches might not be evaluated, which results in partial inference. In -# that case, it might be useful to still emit no-member and other checks for -# the rest of the inferred objects. -ignore-on-opaque-inference=yes +# checks whenever an opaque object is returned when inferring. The inference can +# return multiple potential results while evaluating a Python object, but some +# branches might not be evaluated, which results in partial inference. In that +# case, it might be useful to still emit no-member and other checks for the rest +# of the inferred objects. +ignore-on-opaque-inference = true # List of symbolic message names to ignore for Mixin members. -ignored-checks-for-mixins=no-member, - not-async-context-manager, - not-context-manager, - attribute-defined-outside-init +ignored-checks-for-mixins = ["no-member", "not-async-context-manager", "not-context-manager", "attribute-defined-outside-init"] # List of class names for which member attributes should not be checked (useful # for classes with dynamically set attributes). This supports the use of # qualified names. -ignored-classes=optparse.Values,thread._local,_thread._local,argparse.Namespace +ignored-classes = ["optparse.Values", "thread._local", "_thread._local", "argparse.Namespace"] -# Show a hint with possible names when a member name was not found. The aspect -# of finding the hint is based on edit distance. -missing-member-hint=yes +# Show a hint with possible names when a member name was not found. The aspect of +# finding the hint is based on edit distance. +missing-member-hint = true # The minimum edit distance a name should have in order to be considered a # similar match for a missing member name. -missing-member-hint-distance=1 +missing-member-hint-distance = 1 # The total number of similar names that should be taken in consideration when # showing a hint for a missing member. -missing-member-max-choices=1 +missing-member-max-choices = 1 # Regex pattern to define which classes are considered mixins. -mixin-class-rgx=.*[Mm]ixin +mixin-class-rgx = ".*[Mm]ixin" # List of decorators that change the signature of a decorated function. -signature-mutators= +# signature-mutators = + +[tool.pylint.variables] +# List of additional names supposed to be defined in builtins. Remember that you +# should avoid defining new builtins when possible. +# additional-builtins = + +# Tells whether unused global variables should be treated as a violation. +allow-global-unused-variables = true +# List of names allowed to shadow builtins +# allowed-redefined-builtins = + +# List of strings which can identify a callback function by name. A callback name +# must start or end with one of those strings. +callbacks = ["cb_", "_cb"] -[STRING] +# A regular expression matching the name of dummy variables (i.e. expected to not +# be used). +dummy-variables-rgx = "_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_" -# This flag controls whether inconsistent-quotes generates a warning when the -# character used as a quote delimiter is used inconsistently within a module. -check-quote-consistency=no +# Argument names that match this expression will be ignored. +ignored-argument-names = "_.*|^ignored_|^unused_" -# This flag controls whether the implicit-str-concat should generate a warning -# on implicit string concatenation in sequences defined over several lines. -check-str-concat-over-line-jumps=no +# Tells whether we should check for unused import in __init__ files. +# init-import = + +# List of qualified module names which can have objects that can redefine +# builtins. +redefining-builtins-modules = ["six.moves", "past.builtins", "future.builtins", "builtins", "io"] diff --git a/xclim/cli.py b/xclim/cli.py index 42dcd1f63..2a09f01a9 100644 --- a/xclim/cli.py +++ b/xclim/cli.py @@ -283,7 +283,7 @@ def dataflags(ctx, variables, raise_flags, append, dims, freq): @click.option( "-i", "--info", is_flag=True, help="Prints more details for each indicator." ) -def indices(info): +def indices(information): """List all indicators.""" formatter = click.HelpFormatter() formatter.write_heading("Listing all available indicators for computation.") @@ -297,7 +297,7 @@ def indices(info): right += ( " (" + ", ".join([var["var_name"] for var in indcls.cf_attrs]) + ")" ) - if info: + if information: right += "\n" + indcls.abstract rows.append((left, right)) rows.sort(key=lambda row: row[0]) @@ -466,7 +466,7 @@ def cli(ctx, **kwargs): @cli.result_callback() # noqa @click.pass_context -def write_file(ctx, *args, **kwargs): # noqa +def write_file(ctx, *args, **kwargs): # noqa: W0613 """Write the output dataset to file.""" if ctx.obj["output"] is not None: if ctx.obj["verbose"]: diff --git a/xclim/core/calendar.py b/xclim/core/calendar.py index 1e72fcc45..e63d4ac21 100644 --- a/xclim/core/calendar.py +++ b/xclim/core/calendar.py @@ -1598,18 +1598,18 @@ def get_doys(start, end, inclusive): def _month_is_first_period_month(time, freq): """Returns True if the given time is from the first month of freq.""" if isinstance(time, cftime.datetime): - frqM = xr.coding.cftime_offsets.to_offset("MS") + frq_monthly = xr.coding.cftime_offsets.to_offset("MS") frq = xr.coding.cftime_offsets.to_offset(freq) - if frqM.onOffset(time): + if frq_monthly.onOffset(time): return frq.onOffset(time) - return frq.onOffset(frqM.rollback(time)) + return frq.onOffset(frq_monthly.rollback(time)) # Pandas time = pd.Timestamp(time) - frqM = pd.tseries.frequencies.to_offset("MS") + frq_monthly = pd.tseries.frequencies.to_offset("MS") frq = pd.tseries.frequencies.to_offset(freq) - if frqM.is_on_offset(time): + if frq_monthly.is_on_offset(time): return frq.is_on_offset(time) - return frq.is_on_offset(frqM.rollback(time)) + return frq.is_on_offset(frq_monthly.rollback(time)) def stack_periods( @@ -1635,8 +1635,8 @@ def stack_periods( ---------- da : xr.Dataset or xr.DataArray An xarray object with a `time` dimension. - Must have an uniform timestep length. - Output might be strange if this does not use an uniform calendar (noleap, 360_day, all_leap). + Must have a uniform timestep length. + Output might be strange if this does not use a uniform calendar (noleap, 360_day, all_leap). window : int The length of the moving window as a multiple of ``freq``. stride : int, optional @@ -1652,7 +1652,7 @@ def stack_periods( freq : str Units of ``window``, ``stride`` and ``min_length``, as a frequency string. Must be larger or equal to the data's sampling frequency. - Note that this function offers an easier interface for non uniform period (like years or months) + Note that this function offers an easier interface for non-uniform period (like years or months) but is much slower than a rolling-construct method. dim : str The new dimension name. @@ -1662,7 +1662,8 @@ def stack_periods( align_days : bool When True (default), an error is raised if the output would have unaligned days across periods. If `freq = 'YS'`, day-of-year alignment is checked and if `freq` is "MS" or "QS", we check day-in-month. - Only uniform-calendar will pass the test for `freq='YS'`. For other frequencies, only the `360_day` calendar will work. + Only uniform-calendar will pass the test for `freq='YS'`. + For other frequencies, only the `360_day` calendar will work. This check is ignored if the sampling rate of the data is coarser than "D". pad_value: Any When some periods are shorter than others, this value is used to pad them at the end. @@ -1677,7 +1678,7 @@ def stack_periods( That coordinate is the same for all periods, depending on the choice of ``window`` and ``freq``, it might make sense. But for unequal periods or non-uniform calendars, it will certainly not. If ``stride`` is a divisor of ``window``, the correct timeseries can be reconstructed with :py:func:`unstack_periods`. - The coordinate of `period` is the first timestep of each windows. + The coordinate of `period` is the first timestep of each window. """ from xclim.core.units import ( # Import in function to avoid cyclical imports ensure_cf_units, @@ -1734,9 +1735,9 @@ def stack_periods( ) periods = [] - longest = 0 + # longest = 0 # Iterate over strides, but recompute the full window for each stride start - for begin, strd_slc in da.resample(time=strd_frq).groups.items(): + for _, strd_slc in da.resample(time=strd_frq).groups.items(): win_resamp = time2.isel(time=slice(strd_slc.start, None)).resample(time=win_frq) # Get slice for first group win_slc = win_resamp._group_indices[0] @@ -1749,7 +1750,7 @@ def stack_periods( open_ended = min_slc.stop is None else: # The end of the group slice is None if no outside-group value was found after the last element - # As we added an extra step to time2, we avoid the case where a group ends exactly on the last element of ds. + # As we added an extra step to time2, we avoid the case where a group ends exactly on the last element of ds open_ended = win_slc.stop is None if open_ended: # Too short, we got to the end @@ -1760,7 +1761,8 @@ def stack_periods( and min_length == window and not _month_is_first_period_month(da.time[0].item(), freq) ): - # For annual or quartely frequencies (which can be anchor-based), if the first time is not in the first month of the first period, + # For annual or quartely frequencies (which can be anchor-based), + # if the first time is not in the first month of the first period, # then the first period is incomplete but by a fractional amount. continue periods.append( @@ -1783,7 +1785,7 @@ def stack_periods( m, u = infer_sampling_units(da) lengths = lengths * m lengths.attrs["units"] = ensure_cf_units(u) - # Start points for each periods + remember parameters for unstacking + # Start points for each period and remember parameters for unstacking starts = xr.DataArray( [da.time[slc.start].item() for slc in periods], dims=(dim,), @@ -1873,7 +1875,7 @@ def unstack_periods(da: xr.DataArray | xr.Dataset, dim: str = "period"): f"`unstack_periods` can't find the `{dim}_length` coordinate." ) from err # Get length as number of points - m, u = infer_sampling_units(da.time) + m, _ = infer_sampling_units(da.time) lengths = lengths // m else: # It is acceptable to lose "{dim}_length" if they were all equal diff --git a/xclim/core/indicator.py b/xclim/core/indicator.py index 6590ab9a4..00cc9f414 100644 --- a/xclim/core/indicator.py +++ b/xclim/core/indicator.py @@ -1623,12 +1623,12 @@ def build_indicator_module( ) out = getattr(indicators, name) if reload: - for name, ind in list(out.iter_indicators()): - if name not in objs: + for n, ind in list(out.iter_indicators()): + if n not in objs: # Remove the indicator from the registries and the module del registry[ind._registry_id] # noqa del _indicators_registry[ind.__class__] - del out.__dict__[name] + del out.__dict__[n] else: doc = doc or f"{name.capitalize()} indicators\n" + "=" * (len(name) + 11) try: diff --git a/xclim/core/options.py b/xclim/core/options.py index 1eba36a3f..45eeedacf 100644 --- a/xclim/core/options.py +++ b/xclim/core/options.py @@ -137,7 +137,7 @@ def run_check(*args, **kwargs): return run_check -class set_options: +class set_options: # noqa: C0103 """Set options for xclim in a controlled context. Attributes diff --git a/xclim/core/units.py b/xclim/core/units.py index 1ffc9d567..185f6726a 100644 --- a/xclim/core/units.py +++ b/xclim/core/units.py @@ -1139,10 +1139,10 @@ def dec(func): # Raised when it is not understood, we assume it was a dimensionality try: units.get_dimensionality(dim.replace("dimensionless", "")) - except Exception: + except Exception as e: raise ValueError( f"Relative units for {name} are invalid. Got {dim}. (See stacktrace for more information)." - ) + ) from e @wraps(func) def wrapper(*args, **kwargs): diff --git a/xclim/core/utils.py b/xclim/core/utils.py index 89304b5ce..d582b5be2 100644 --- a/xclim/core/utils.py +++ b/xclim/core/utils.py @@ -136,10 +136,11 @@ def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): msg = ( - f"`{func.__name__}` is deprecated{' from version {}'.format(from_version) if from_version else ''} " + f"`{func.__name__}` is deprecated" + f"{' from version {}'.format(from_version) if from_version else ''} " "and will be removed in a future version of xclim" - f"{'. Use `{}` instead'.format(suggested if suggested else '')}. " - f"Please update your scripts accordingly." + f"{'. Use `{}` instead'.format(suggested) if suggested else ''}. " + "Please update your scripts accordingly." ) warnings.warn( msg, diff --git a/xclim/ensembles/_filters.py b/xclim/ensembles/_filters.py index ef0e8f969..6923173da 100644 --- a/xclim/ensembles/_filters.py +++ b/xclim/ensembles/_filters.py @@ -47,7 +47,7 @@ def _concat_hist(da, **hist): raise ValueError("Too many values in hist scenario.") # Scenario dimension, and name of the historical scenario - ((dim, name),) = hist.items() + ((dim, _),) = hist.items() # Select historical scenario and drop it from the data h = da.sel(**hist).dropna("time", how="all") diff --git a/xclim/sdba/processing.py b/xclim/sdba/processing.py index f6d833ae8..7866956c2 100644 --- a/xclim/sdba/processing.py +++ b/xclim/sdba/processing.py @@ -46,10 +46,10 @@ def adapt_freq( Parameters ---------- - ds : xr.Dataset - With variables : "ref", Target/reference data, usually observed data, and "sim", Simulated data. - dim : str - Dimension name. + ref : xr.Dataset + Target/reference data, usually observed data, with a "time" dimension. + sim : xr.Dataset + Simulated data, with a "time" dimension. group : str or Grouper Grouping information, see base.Grouper thresh : str diff --git a/xclim/sdba/properties.py b/xclim/sdba/properties.py index e729a13ee..94bc10ab1 100644 --- a/xclim/sdba/properties.py +++ b/xclim/sdba/properties.py @@ -1112,7 +1112,7 @@ def _decorrelation_length( corr = _pairwise_spearman(da, dims) - dists, mn, mx = _pairwise_haversine_and_bins( + dists, _, _ = _pairwise_haversine_and_bins( corr.cf["longitude"].values, corr.cf["latitude"].values, transpose=True ) diff --git a/xclim/testing/utils.py b/xclim/testing/utils.py index c15a92054..82b63d631 100644 --- a/xclim/testing/utils.py +++ b/xclim/testing/utils.py @@ -202,7 +202,8 @@ def _get( local_md5 = file_md5_checksum(local_file) try: url = "/".join((github_url, "raw", branch, md5_name.as_posix())) - logger.info(f"Attempting to fetch remote file md5: {md5_name.as_posix()}") + msg = f"Attempting to fetch remote file md5: {md5_name.as_posix()}" + logger.info(msg) urlretrieve(url, md5_file) # nosec with open(md5_file) as f: remote_md5 = f.read() @@ -235,7 +236,7 @@ def _get( local_file.parent.mkdir(exist_ok=True, parents=True) url = "/".join((github_url, "raw", branch, fullname.as_posix())) - logger.info(f"Fetching remote file: {fullname.as_posix()}") + logger.info("Fetching remote file: {}" % fullname.as_posix()) try: urlretrieve(url, local_file) # nosec except HTTPError as e: @@ -256,7 +257,7 @@ def _get( raise FileNotFoundError(msg) from e try: url = "/".join((github_url, "raw", branch, md5_name.as_posix())) - logger.info(f"Fetching remote file md5: {md5_name.as_posix()}") + logger.info("Fetching remote file md5: {}" % md5_name.as_posix()) urlretrieve(url, md5_file) # nosec except (HTTPError, URLError) as e: msg = (