### Logging Configuration Example Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/configuration/all-options.md Example of how to configure logging options in a Pylint configuration file. This sets the logging format style and the modules to check. ```toml [tool.pylint.logging] # Possible choices: ['old', 'new'] logging-format-style = "old" logging-modules = ["logging"] ``` -------------------------------- ### Example Pylint Configuration Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/configuration/all-options.md This TOML snippet shows a comprehensive example of Pylint configuration within the [tool.pylint] section. It demonstrates default values for many options. ```toml [tool.pylint.main] analyse-fallback-blocks = false clear-cache-post-run = false confidence = ["HIGH", "CONTROL_FLOW", "INFERENCE", "INFERENCE_FAILURE", "UNDEFINED"] disable = ["bad-inline-option", "consider-using-augmented-assign", "deprecated-pragma", "file-ignored", "locally-disabled", "prefer-typing-namedtuple", "raw-checker-failed", "suppressed-message", "use-implicit-booleaness-not-comparison-to-string", "use-implicit-booleaness-not-comparison-to-zero", "use-symbolic-message-instead", "useless-suppression"] enable = [] evaluation = "max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10))" exit-zero = false extension-pkg-allow-list = [] extension-pkg-whitelist = [] fail-on = [] fail-under = 10 files = [] from-stdin = false ignore = ["CVS"] ignore-paths = [] ignore-patterns = ["^\\.#"] ignored-modules = [] jobs = 1 limit-inference-results = 100 load-plugins = [] msg-template = "" # output-format = persistent = true prefer-stubs = false py-version = "sys.version_info[:2]" recursive = false reports = false score = true source-roots = [] unsafe-load-any-extension = false ``` -------------------------------- ### Install Pylint Source: https://github.com/pylint-dev/pylint/blob/main/README.rst Install Pylint using pip. For spelling checks, install with the 'spelling' extra. ```sh pip install pylint ``` ```sh pip install pylint[spelling] ``` -------------------------------- ### Install Pylint with Pip Source: https://github.com/pylint-dev/pylint/blob/main/doc/short_text_installation.md Use this command to install the basic Pylint package for command-line use. ```default pip install pylint ``` -------------------------------- ### Message Template Examples Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/usage/output.md Examples of --msg-template for different output styles, including default, Visual Studio compatible, and parseable formats. ```bash {path}:{line}:{column}: {msg_id}: {msg} ({symbol}) ``` ```bash {path}({line}): [{msg_id}{obj}] {msg} ``` ```bash {path}:{line}: [{msg_id}({symbol}), {obj}] {msg} ``` -------------------------------- ### Clone and Install Astroid for Development Source: https://github.com/pylint-dev/pylint/blob/main/doc/development_guide/contributor_guide/tests/install.md Clone the astroid repository and install it in an editable mode alongside Pylint. This is necessary when testing changes in astroid itself. ```bash # Suppose you're in the pylint directory git clone https://github.com/pylint-dev/astroid.git python3 -m pip install -e astroid/ ``` -------------------------------- ### Build Pylint Documentation Source: https://github.com/pylint-dev/pylint/blob/main/doc/development_guide/contributor_guide/contribute.md Commands to install documentation dependencies and build the HTML documentation for Pylint using make. ```bash make -C doc/ install-dependencies ``` ```bash make -C doc/ html ``` -------------------------------- ### Example Miscellaneous Configuration Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/configuration/all-options.md Shows default values for miscellaneous checker options in a TOML configuration file. ```toml [tool.pylint.miscellaneous] check-fixme-in-docstring = false notes = ["FIXME", "XXX", "TODO"] notes-rgx = "" ``` -------------------------------- ### Parseable Output Format Example Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/usage/output.md Demonstrates the 'parseable' output format, which is recognized by many editors and development tools. ```text ************* Module pylint.checkers.format W: 50: Too long line (86/80) W:108: Operator not followed by a space print >>sys.stderr, 'Unable to match %r', line ^ W:141: Too long line (81/80) W: 74:searchall: Unreachable code W:171:FormatChecker.process_tokens: Redefining built-in (type) W:150:FormatChecker.process_tokens: Too many local variables (20/15) W:150:FormatChecker.process_tokens: Too many branches (13/12) ``` -------------------------------- ### Example Refactoring Configuration Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/configuration/all-options.md Shows default values for refactoring checker options in a TOML configuration file. ```toml [tool.pylint.refactoring] max-nested-blocks = 5 never-returning-functions = ["sys.exit", "argparse.parse_error"] suggest-join-with-non-empty-separator = true ``` -------------------------------- ### Google Style Parameter Documentation Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/checkers/extensions.md Example of documenting parameters, types, return values, and exceptions using Google style in a docstring. ```python def function_foo(x, y, z): '''function foo ... Args: x (int): bla x y (float): bla y z (int): bla z Returns: float: sum Raises: OSError: bla ''' return x + y + z ``` -------------------------------- ### Install Release Dependencies Source: https://github.com/pylint-dev/pylint/blob/main/doc/development_guide/contributor_guide/release.md Installs the exact release dependencies, including the pinned astroid version, required for testing. Ensure this pinned version is installed before running tbump to avoid CI failures. ```bash pip3 install -r requirements_test.txt ``` -------------------------------- ### Example Pylint Imports Configuration Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/configuration/all-options.md This TOML snippet shows a complete example of the default configuration for the Pylint imports checker. It demonstrates how to set various options related to module imports. ```toml [tool.pylint.imports] allow-any-import-level = [] allow-reexport-from-package = false allow-wildcard-with-all = false deprecated-modules = [] ext-import-graph = "" import-graph = "" int-import-graph = "" known-first-party = [] known-standard-library = [] known-third-party = ["enchant"] preferred-modules = [] ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/pylint-dev/pylint/blob/main/doc/development_guide/contributor_guide/tests/install.md Enable pre-commit hooks to automatically format code before each commit. Run this command in the Pylint root directory. ```bash pre-commit install ``` -------------------------------- ### Example Similarities Checker Configuration Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/configuration/all-options.md Configure the Similarities checker to ignore comments, docstrings, imports, and signatures, and set the minimum similarity lines. This example uses default values. ```toml [tool.pylint.similarities] ignore-comments = true ignore-docstrings = true ignore-imports = true ignore-signatures = true min-similarity-lines = 4 ``` -------------------------------- ### Correct f-string Formatting Example Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/convention/consider-using-f-string.md Shows the preferred f-string syntax for the same formatting task as the problematic examples. This code represents the recommended way to format strings in Python 3.6+. ```python menu = ("eggs", "spam", 42.4) f_string_order = f"{menu[0]} and {menu[1]}: {menu[2]:0.2f} ¤" ``` -------------------------------- ### Install Pylint with Spell Checking Support Source: https://github.com/pylint-dev/pylint/blob/main/doc/short_text_installation.md Install Pylint with the optional 'spelling' extra to enable spell checking. Ensure the enchant C library is installed separately if needed. ```sh pip install pylint[spelling] ``` -------------------------------- ### Correct Code Example Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/information/suppressed-message.md This is the correct code example provided in the documentation, contrasting with the problematic code that triggers the 'suppressed-message'. ```python """Instead of a single string somewhere in the file, write a module docstring!""" ``` -------------------------------- ### Set Up Pylint Development Environment Source: https://github.com/pylint-dev/pylint/blob/main/doc/development_guide/contributor_guide/tests/install.md Install Pylint in an editable mode within a virtual environment for development and testing. This ensures your local changes are reflected immediately. ```bash cd pylint python3 -m venv venv source venv/bin/activate pip install -r requirements_test_min.txt pip install -e . ``` -------------------------------- ### Example Spelling Checker Configuration Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/configuration/all-options.md Configure the Spelling checker, setting the maximum number of suggestions, dictionary, ignored directives and words, and whether to store unknown words. This example uses default values. ```toml [tool.pylint.spelling] max-spelling-suggestions = 4 # Possible choices: Values from 'enchant.Broker().list_dicts()' depending on your local enchant installation spelling-dict = "" spelling-ignore-comment-directives = "fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy:" spelling-ignore-words = "" spelling-private-dict-file = "" spelling-store-unknown-words = false ``` -------------------------------- ### Correct Code with Comments Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/refactor/empty-comment.md These examples demonstrate how to write valid comments, ensuring that a '#' symbol is always followed by descriptive text. ```python # comment ``` ```python x = 0 # comment ``` -------------------------------- ### Method Arguments Timeout Configuration Example Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/configuration/all-options.md Example of how to configure timeout methods for the MethodArgs checker in Pylint. This specifies which methods require a timeout parameter. ```toml [tool.pylint.method_args] 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"] ``` -------------------------------- ### Install Pylint with Apt-get Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/installation/command_line_installation.md Install Pylint on Debian-based systems using the apt-get package manager. This method may also lag behind the latest releases. ```sh sudo apt-get install pylint ``` -------------------------------- ### Numpy Style Parameter Documentation Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/checkers/extensions.md Example of documenting parameters, types, return values, and exceptions using Numpy style in a docstring. ```python def function_foo(x, y, z): '''function foo ... Parameters ---------- x: int bla x y: float bla y z: int bla z Returns ------- float sum Raises ------ OSError bla ''' return x + y + z ``` -------------------------------- ### Ungrouped Imports Example Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/convention/ungrouped-imports.md This example shows problematic code with ungrouped imports and the corrected version. Ensure imports from the same package are grouped together. ```python import logging import os import sys import logging.config # [ungrouped-imports] from logging.handlers import WatchedFileHandler ``` ```python import logging import logging.config import os import sys from logging.handlers import FileHandler ``` -------------------------------- ### Sphinx Style Parameter Documentation Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/checkers/extensions.md Example of documenting parameters, types, return values, and exceptions using Sphinx style in a docstring. ```python def function_foo(x, y, z): '''function foo ... :param x: bla x :type x: int :param y: bla y :type y: float :param int z: bla z :return: sum :rtype: float :raises OSError: bla ''' return x + y + z ``` -------------------------------- ### Skipping Parameter Documentation (Google Style) Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/checkers/extensions.md Example using Google style to indicate that other parameters are documented elsewhere, for instance, in a superclass. ```python def callback(x, y, z): '''Google style docstring for callback ... Args: x (int): bla x For the other parameters, see :class:`MyFrameworkUsingAndDefiningCallback` ''' return x + y + z ``` -------------------------------- ### Correct __future__ Import Placement Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/warning/misplaced-future.md This example demonstrates the correct placement of a __future__ import statement, ensuring it is the first non-docstring statement in the module. ```python from __future__ import print_function import sys ``` -------------------------------- ### Remove Redundant Return Documentation Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/warning/redundant-returns-doc.md This example shows problematic code with redundant return documentation and the corrected version. Ensure return documentation is only present when necessary. ```python def print_fruits(fruits): """Print list of fruits Returns ------- str """ print(fruits) return None ``` ```python def print_fruits(fruits): """Print list of fruits Returns ------- str """ print(fruits) return ",".join(fruits) ``` -------------------------------- ### Class with Sufficient Public Methods Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/refactor/too-few-public-methods.md This example demonstrates a class that adheres to the R0903 rule by having multiple public methods, thus avoiding the warning. ```python class Worm: def __init__(self, name: str, fruit_of_residence: Fruit): self.name = name self.fruit_of_residence = fruit_of_residence def bore(self): print(f"{self.name} is boring into {self.fruit_of_residence}") def wiggle(self): print(f"{self.name} wiggle around wormily.") ``` -------------------------------- ### Skipping Parameter Documentation (Sphinx Style) Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/checkers/extensions.md Example using Sphinx style to indicate that other parameters are documented elsewhere, for instance, in a superclass. ```python def callback(x, y, z): '''Sphinx style docstring for callback ... :param x: bla x :type x: int For the other parameters, see :class:`MyFrameworkUsingAndDefiningCallback` ''' return x + y + z ``` -------------------------------- ### Constructor Parameter Documentation (__init__ Docstring) Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/checkers/extensions.md Demonstrates documenting constructor parameters in the __init__ docstring using Google style. ```python class ClassBar(object): def __init__(self, x, y): '''Google style docstring bar Args: x (float): bla x y (int): bla y ''' pass ``` -------------------------------- ### Incorrect Indentation Example Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/warning/bad-indentation.md This snippet shows code with incorrect indentation, which will trigger the W0311 warning. Ensure consistent use of spaces or tabs according to your project's style guide. ```python if input(): print('yes') # [bad-indentation] ``` -------------------------------- ### Fixing Import Error E0401 Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/error/import-error.md When encountering an 'Unable to import %s' error, check if the module is installed and if the import statement has any typos. This example shows a common mistake with 'patlib' versus the correct 'pathlib'. ```python from patlib import Path # [import-error] ``` ```python from pathlib import Path ``` -------------------------------- ### Prepare and Run Primer Tests for External Repositories Source: https://github.com/pylint-dev/pylint/blob/main/doc/development_guide/contributor_guide/tests/launching_test.md These commands prepare the environment by cloning repositories and then run the primer tests to assess Pylint's impact on external codebases. ```bash python tests/primer/__main__.py prepare --clone ``` ```bash python tests/primer/__main__.py run --type=pr ``` -------------------------------- ### Python Docstring First Line Empty Example Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/convention/docstring-first-line-empty.md This snippet demonstrates a Python function with a docstring that incorrectly starts with a blank line, triggering the C0199 error. Ensure the first line of your docstring is not empty. ```python def foo(): # [docstring-first-line-empty] """ Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book """ ``` -------------------------------- ### Configure Expected Job Count Source: https://github.com/pylint-dev/pylint/blob/main/doc/development_guide/contributor_guide/tests/writing_test.md Example of a .json file used in functional configuration tests to specify a change in the 'jobs' configuration value. ```json "jobs": 10, ``` -------------------------------- ### Constructor Parameter Documentation (Class Docstring) Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/checkers/extensions.md Demonstrates documenting constructor parameters in the class docstring using Sphinx style. ```python class ClassFoo(object): '''Sphinx style docstring foo :param float x: bla x :param y: bla y :type y: int ''' def __init__(self, x, y): pass ``` -------------------------------- ### Running a Pylint Plugin Source: https://github.com/pylint-dev/pylint/blob/main/doc/development_guide/how_tos/plugins.md Plugins can be loaded by placing their module in the PYTHONPATH and using the --load-plugins option with the pylint command. ```bash $ pylint -E --load-plugins hello_plugin foo.py ``` -------------------------------- ### Module-Level Redefinition Example Source: https://github.com/pylint-dev/pylint/blob/main/doc/data/messages/r/redefined-builtin/details.rst This example demonstrates shadowing the built-in `id` at the module level. Pylint's `allowed-redefined-builtins` option does not prevent this. ```python # module_level_redefine.py id = 1 # Shadows the built-in `id` ``` -------------------------------- ### Performance Comparison: 'yield from' vs. Manual Yielding Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/refactor/use-yield-from.md Demonstrates the performance difference between using 'yield from' and manually yielding elements in a loop. 'yield from' is marginally faster. ```sh $ python3 -m timeit "def yield_from(): yield from range(100)" "for _ in yield_from(): pass" 100000 loops, best of 5: 2.44 usec per loop $ python3 -m timeit "def yield_loop():" " for item in range(100): yield item" "for _ in yield_loop(): pass" 100000 loops, best of 5: 2.49 usec per loop ``` -------------------------------- ### Problematic Code: Too Few Format Arguments Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/error/too-few-format-args.md This example shows a format string with two placeholders ({0} and {1}) but only one argument provided. This will raise an E1306 error. ```python print("Today is {0}, so tomorrow will be {1}".format("Monday")) # [too-few-format-args] ``` -------------------------------- ### Correct File Name Example Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/warning/non-ascii-file-name.md This code snippet shows examples of file names that do not contain non-ASCII characters and are therefore considered correct. ```python ``` ```python ``` ```python ``` -------------------------------- ### Running Pylint with a Transform Plugin Source: https://github.com/pylint-dev/pylint/blob/main/doc/development_guide/how_tos/transform_plugins.md This bash command demonstrates how to load and run Pylint with the custom `warning_plugin`, resolving the 'no-member' errors previously encountered. ```bash amitdev$ pylint -E --load-plugins warning_plugin Lib/warnings.py amitdev$ ``` -------------------------------- ### Pylint Configuration Example Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/configuration/all-options.md This TOML snippet shows default Pylint configuration options for naming styles and regular expressions. It demonstrates how to set naming conventions for arguments, attributes, classes, constants, functions, methods, modules, and variables. ```toml [tool.pylint.basic] # Possible choices: ['snake_case', 'camelCase', 'PascalCase', 'UPPER_CASE', 'any'] argument-naming-style = "snake_case" # argument-rgx = # Possible choices: ['snake_case', 'camelCase', 'PascalCase', 'UPPER_CASE', 'any'] attr-naming-style = "snake_case" # attr-rgx = bad-names = ["foo", "bar", "baz", "toto", "tutu", "tata"] bad-names-rgxs = [] # Possible choices: ['snake_case', 'camelCase', 'PascalCase', 'UPPER_CASE', 'any'] class-attribute-naming-style = "any" # class-attribute-rgx = # Possible choices: ['snake_case', 'camelCase', 'PascalCase', 'UPPER_CASE', 'any'] class-const-naming-style = "UPPER_CASE" # class-const-rgx = # Possible choices: ['snake_case', 'camelCase', 'PascalCase', 'UPPER_CASE', 'any'] class-naming-style = "PascalCase" # class-rgx = # Possible choices: ['snake_case', 'camelCase', 'PascalCase', 'UPPER_CASE', 'any'] const-naming-style = "UPPER_CASE" # const-rgx = docstring-min-length = -1 # Possible choices: ['snake_case', 'camelCase', 'PascalCase', 'UPPER_CASE', 'any'] function-naming-style = "snake_case" # function-rgx = good-names = ["i", "j", "k", "ex", "Run", "_"] good-names-rgxs = [] include-naming-hint = false # Possible choices: ['snake_case', 'camelCase', 'PascalCase', 'UPPER_CASE', 'any'] inlinevar-naming-style = "any" # inlinevar-rgx = # Possible choices: ['snake_case', 'camelCase', 'PascalCase', 'UPPER_CASE', 'any'] method-naming-style = "snake_case" # method-rgx = # Possible choices: ['snake_case', 'camelCase', 'PascalCase', 'UPPER_CASE', 'any'] module-naming-style = "snake_case" # module-rgx = name-group = [] no-docstring-rgx = "^ _" # paramspec-rgx = property-classes = ["abc.abstractproperty"] # typealias-rgx = # typevar-rgx = # typevartuple-rgx = # Possible choices: ['snake_case', 'camelCase', 'PascalCase', 'UPPER_CASE', 'any'] variable-naming-style = "snake_case" # variable-rgx = ``` -------------------------------- ### Install Pylint with Conda Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/installation/command_line_installation.md Install Pylint using the conda package manager. Note that conda packages may lag behind the latest releases. ```sh conda install pylint ``` -------------------------------- ### Demonstrate Suppressed Message in Python Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/information/suppressed-message.md This example shows how to trigger the 'suppressed-message' by using pylint enable/disable comments. It's a contrived example to illustrate the message's behavior. ```python ### This is a contrived example, to show how suppressed-message works. ### First we enable all messages # pylint: enable=all ### Here we disable two messages so we get two warnings # pylint: disable=locally-disabled, useless-suppression # [suppressed-message, suppressed-message] ### Here we disable a message, so we get a warning for suppressed-message again. "A" # pylint: disable=pointless-statement # [suppressed-message, suppressed-message] ``` -------------------------------- ### Using Globbing Patterns with Pylint Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/usage/run.md Demonstrates how to use globbing patterns to specify multiple directories and files for Pylint analysis. This allows for flexible selection of code to lint. ```bash pylint [options] packages/*/src ``` -------------------------------- ### Example Python Code with Mixed Naming Styles Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/convention/invalid-name.md This example demonstrates a Python module with functions adhering to both snake_case and CamelCase. Pylint will detect the dominant style and warn about violations. ```python def valid_snake_case(arg): ... def InvalidCamelCase(arg): ... def more_valid_snake_case(arg): ... ``` -------------------------------- ### Correct Code: Sufficient Format Arguments Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/error/too-few-format-args.md This example demonstrates the correct usage where the number of arguments matches the number of placeholders in the format string, resolving the E1306 error. ```python print("Today is {0}, so tomorrow will be {1}".format("Monday", "Tuesday")) ``` -------------------------------- ### Global Variable Redefinition Example Source: https://github.com/pylint-dev/pylint/blob/main/doc/data/messages/r/redefined-builtin/details.rst This example shows shadowing the built-in `len` using a global variable within a function. Pylint's `allowed-redefined-builtins` option is not effective for global redefinitions. ```python # global_variable_redefine.py def my_func(): global len len = 1 # Shadows the built-in `len` ``` -------------------------------- ### Pylint Plugin with Configuration Loading Source: https://github.com/pylint-dev/pylint/blob/main/doc/development_guide/how_tos/plugins.md A plugin can optionally define a 'load_configuration' function to load custom settings after Pylint reads its configuration file and command-line arguments. This example shows how to extend good names and blacklist directories. ```python from typing import TYPE_CHECKING import astroid if TYPE_CHECKING: from pylint.lint import PyLinter def register(linter: "PyLinter") -> None: """This required method auto registers the checker during initialization. :param linter: The linter to register the checker to. """ print('Hello world') def load_configuration(linter): name_checker = get_checker(linter, NameChecker) # We consider as good names of variables Hello and World name_checker.config.good_names += ('Hello', 'World') # We ignore bin directory linter.config.black_list += ('bin',) ``` -------------------------------- ### Safely use exec with restricted globals Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/warning/exec-used.md This example shows a safer way to use 'exec' by explicitly defining allowed globals and locals. It demonstrates how to restrict built-in functions to mitigate security risks. ```python def get_user_code(name): return input(f"Enter code to be executed please, {name}: ") username = "Ada" # If the globals dictionary does not contain a value for the key __builtins__, # all builtins are allowed. You need to be explicit about it being disallowed. allowed_globals = {"__builtins__": {}} allowed_locals = {} # pylint: disable-next=exec-used exec(get_user_code(username), allowed_globals, allowed_locals) ``` -------------------------------- ### Comprehensive Pylint Block Disable Example Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/message_control.md This example showcases various ways to use pylint pragmas for disabling and enabling messages within different code structures like functions, loops, and conditional blocks. ```python """pylint option block-disable""" __revision__ = None class Foo(object): """block-disable test""" def __init__(self): pass def meth1(self, arg): """this issues a message""" print(self) def meth2(self, arg): """and this one not""" # pylint: disable=unused-argument print(self\ + "foo") def meth3(self): """test one line disabling""" # no error print(self.bla) # pylint: disable=no-member # error print(self.blop) def meth4(self): """test re-enabling""" # pylint: disable=no-member # no error print(self.bla) print(self.blop) # pylint: enable=no-member # error print(self.blip) def meth5(self): """test IF sub-block re-enabling""" # pylint: disable=no-member # no error print(self.bla) if self.blop: # pylint: enable=no-member # error print(self.blip) else: # no error print(self.blip) # no error print(self.blip) def meth6(self): """test TRY/EXCEPT sub-block re-enabling""" # pylint: disable=no-member # no error print(self.bla) try: # pylint: enable=no-member # error print(self.blip) except UndefinedName: # pylint: disable=undefined-variable # no error print(self.blip) # no error print(self.blip) def meth7(self): """test one line block opening disabling""" if self.blop: # pylint: disable=no-member # error print(self.blip) else: # error print(self.blip) # error print(self.blip) def meth8(self): """test late disabling""" # error print(self.blip) # pylint: disable=no-member # no error print(self.bla) print(self.blop) def meth9(self): """test next line disabling""" # no error # pylint: disable-next=no-member print(self.bla) # error print(self.blop) ``` -------------------------------- ### Configuration to Load Comparison Placement Plugin Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/convention/misplaced-comparison-constant.md This INI configuration snippet shows how to load the comparison-placement extension, which enables the misplaced-comparison-constant check. ```ini [MAIN] load-plugins=pylint.extensions.comparison_placement ``` -------------------------------- ### Load and Use Design Checker Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/checkers/extensions.md Demonstrates how to load the design checker plugin and run Pylint on a Python file. The output shows the 'too-complex' warning for a function exceeding the default complexity limit. ```python def f10(): """McCabe rating: 11""" myint = 2 if myint == 5: return myint elif myint == 6: return myint elif myint == 7: return myint elif myint == 8: return myint elif myint == 9: return myint elif myint == 10: if myint == 8: while True: return True elif myint == 8: with myint: return 8 else: if myint == 2: return myint return myint return myint ``` ```bash $ pylint a.py --load-plugins=pylint.extensions.mccabe R:1: 'f10' is too complex. The McCabe rating is 11 (too-complex) ``` ```bash $ pylint a.py --load-plugins=pylint.extensions.mccabe --max-complexity=50 ``` -------------------------------- ### Unrecognized Inline Option Example Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/error/unrecognized-inline-option.md This snippet shows an example of problematic code that triggers the 'Unrecognized file option' error due to an unknown inline option. Use correct Pylint options to avoid this error. ```python # pylint:applesoranges=1 ``` -------------------------------- ### Handling fixme notes in fixed.py Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/warning/fixme.md This example shows a comment in `fixed.py` that is no longer needed because the issue has been fixed. ```python # The issue was fixed: no longer need the comment ``` -------------------------------- ### Build OSS-Fuzz image and fuzz targets Source: https://github.com/pylint-dev/pylint/blob/main/doc/development_guide/contributor_guide/oss_fuzz.md Commands to clone the OSS-Fuzz repository and build the Docker image and fuzz targets for astroid. ```bash git clone https://github.com/google/oss-fuzz.git cd oss-fuzz python infra/helper.py build_image astroid python infra/helper.py build_fuzzers astroid ``` -------------------------------- ### Nonlocal without binding Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/error/nonlocal-without-binding.md Use `nonlocal` only when the variable is defined in an enclosing scope. This example shows incorrect usage. ```python class Fruit: def get_color(self): nonlocal colors # [nonlocal-without-binding] ``` -------------------------------- ### Setting Project Name Source: https://github.com/pylint-dev/pylint/blob/main/doc/additional_tools/pyreverse/configuration.md Assign a name to the project, which will be appended to the output file names. ```default pyreverse --project ``` -------------------------------- ### Handling fixme notes in bug_tracker.py Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/warning/fixme.md This example shows a comment in `bug_tracker.py` that is no longer needed because the issue has been added to a bug tracker. ```python # The issue was added to the bug tracker: no longer need the comment ``` -------------------------------- ### Correct Code: Consistent Variable Type Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/refactor/redefined-variable-type.md This example demonstrates correct usage where the variable 'x' maintains its integer type. ```python x = 1 x = 2 ``` -------------------------------- ### Correct Code: Implementing Subscription Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/error/unsubscriptable-object.md This snippet shows how to correctly implement subscription for a class by defining the `__getitem__` method. This allows instances of the class to be subscripted. ```python class Fruit: def __init__(self): self.colors = ["red", "orange", "yellow"] def __getitem__(self, idx): return self.colors[idx] Fruit()[1] ``` -------------------------------- ### Correct nonlocal usage Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/error/nonlocal-without-binding.md This example demonstrates the correct way to use `nonlocal` by ensuring the variable is defined in an enclosing scope. ```python class Fruit: colors = ["red", "green"] def get_color(self): nonlocal colors ``` -------------------------------- ### Run Pylint, Pyreverse, and Symilar from Python Source: https://github.com/pylint-dev/pylint/blob/main/doc/development_guide/api/index.md Import and call the respective functions to execute Pylint, pyreverse, or symilar from your Python code. Pass command-line arguments as strings. ```python from pylint import run_pylint, run_pyreverse, run_symilar run_pylint("--disable=C", "myfile.py") run_pyreverse(...) run_symilar(...) ``` -------------------------------- ### Disable Message on a Block Starting Line Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/message_control.md When a pragma is on the same line as a block-starting statement (like 'if'), it applies only to that specific line. ```python if self.blop: # pylint: disable=no-member; applies only to this line # Here we get an error print(self.blip) else: # error print(self.blip) ``` -------------------------------- ### Advanced exec security with custom builtins Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/warning/exec-used.md This example illustrates a more advanced security measure for 'exec' by providing a custom '__builtins__' dictionary that disallows certain functions like 'print' while allowing others like '__import__' and 'open'. It then demonstrates a scenario where a malicious script is written and executed, showing that even with restrictions, careful consideration is needed. ```python import textwrap def forbid_print(*args): raise ValueError("This is raised when a print is used") allowed_globals = { "__builtins__": { "__import__": __builtins__.__import__, "open": __builtins__.open, "print": forbid_print, } } exec( textwrap.dedent( """ import textwrap with open("nefarious.py", "w") as f: f.write(textwrap.dedent(''' def connive(): print("Here's some code as nefarious as imaginable") ''')) import nefarious nefarious.connive() # This will NOT raise a ValueError """ ), allowed_globals, ) ``` -------------------------------- ### Configure Overgeneral Exceptions in Pylint Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/configuration/all-options.md Use this configuration to specify exceptions that should trigger a warning when caught. This example shows the default values. ```toml [tool.pylint.exceptions] overgeneral-exceptions = ["builtins.BaseException", "builtins.Exception"] ``` -------------------------------- ### Example Pylint Classes Configuration Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/configuration/all-options.md This TOML snippet shows how to configure Pylint's 'classes' checker options. It demonstrates setting boolean flags and lists of strings for various checks. ```toml [tool.pylint.classes] check-protected-access-in-special-methods = false defining-attr-methods = ["__init__", "__new__", "setUp", "asyncSetUp", "__post_init__"] exclude-protected = ["_asdict", "_fields", "_replace", "_source", "_make", "os._exit"] valid-classmethod-first-arg = ["cls"] valid-metaclass-classmethod-first-arg = ["mcs"] ``` -------------------------------- ### Run Tox with Environment Recreation Source: https://github.com/pylint-dev/pylint/blob/main/doc/development_guide/contributor_guide/tests/launching_test.md Use the --recreate flag with tox to force re-downloading dependencies and rebuilding environments. This is useful when dependencies like astroid are updated. ```bash python -m tox --recreate # The entire tox environment will be recreated ``` ```bash python -m tox --recreate -e py310 # The python 3.10 tox environment will be recreated ``` -------------------------------- ### Display Pylint Help Information Source: https://github.com/pylint-dev/pylint/blob/main/doc/tutorial.md Use the `--help` argument to view available command-line options for Pylint. For more detailed information, use `--long-help`. ```console tutor Desktop$ pylint --help ``` ```default Commands: --help-msg= --generate-toml-config Messages control: --disable= Reports: --reports= --output-format= ``` ```console tutor Desktop$ pylint --long-help ``` ```default Output: Using the default text output, the message format is : MESSAGE_TYPE: LINE_NUM:[OBJECT:] MESSAGE There are 5 kind of message types : * (C) convention, for programming standard violation * (R) refactor, for bad code smell * (W) warning, for python specific problems * (E) error, for probable bugs in the code * (F) fatal, if an error occurred which prevented pylint from doing further processing. ``` -------------------------------- ### Load Deprecated Builtins Extension and Configure Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/checkers/extensions.md Load the deprecated builtins extension and specify which built-in functions to warn about using the 'bad-functions' option. ```bash $ pylint a.py --load-plugins=pylint.extensions.bad_builtin --bad-functions=apply,reduce ... ``` -------------------------------- ### Benchmarking yield from vs. yield loop Source: https://github.com/pylint-dev/pylint/blob/main/doc/data/messages/u/use-yield-from/details.rst Compares the performance of using 'yield from' versus a manual 'for' loop with 'yield' for delegating to a generator. 'yield from' is shown to be marginally faster. ```sh $ python3 -m timeit "def yield_from(): yield from range(100)" "for _ in yield_from(): pass" 100000 loops, best of 5: 2.44 usec per loop ``` ```sh $ python3 -m timeit "def yield_loop():" " for item in range(100): yield item" "for _ in yield_loop(): pass" 100000 loops, best of 5: 2.49 usec per loop ``` -------------------------------- ### Problematic Code with Too Many Locals Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/refactor/too-many-locals.md This example demonstrates a function with a high number of local variables, which would trigger the too-many-locals warning. ```python from childhood import Child, Sweet def handle_sweets(infos): # Create children children = [Child(info) for info in infos] number_of_sweets = 87 sweets = [Sweet() * number_of_sweets] number_of_sweet_per_child = 5 money = 45.0 sweets_given = 0 time_to_eat_sweet = 54 price_of_sweet = 0.42 # distribute sweet for child in children: sweets_given += number_of_sweet_per_child child.give(sweets[number_of_sweet_per_child:]) # calculate prices cost_of_children = sweets_given * price_of_sweet # Calculate remaining money remaining_money = money - cost_of_children # Calculate time it took time_it_took_assuming_parallel_eating = ( time_to_eat_sweet * number_of_sweet_per_child ) print( f"{children} ate {cost_of_children}¤ of sweets in {time_it_took_assuming_parallel_eating}, " f"you still have {remaining_money}" ) ``` -------------------------------- ### Correct threading.Thread Instantiation Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/warning/bad-thread-instantiation.md This code shows the correct way to instantiate `threading.Thread` by explicitly passing the `target` function and its arguments. This avoids the Pylint W1506 warning. ```python import threading def thread_target(n): print(n**2) thread = threading.Thread(target=thread_target, args=(10,)) thread.start() ``` -------------------------------- ### Problematic Code: Redefined Variable Type Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/refactor/redefined-variable-type.md This example shows a variable 'x' being assigned an integer and then a string, triggering the R0204 warning. ```python x = 1 x = "2" # [redefined-variable-type] ``` -------------------------------- ### Problematic Code with Empty Comments Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/refactor/empty-comment.md These examples show lines with '#' symbols that are not followed by actual comment text, triggering the R2044 warning. ```python # ``` ```python x = 0 # ``` -------------------------------- ### Output Directory Configuration Source: https://github.com/pylint-dev/pylint/blob/main/doc/additional_tools/pyreverse/configuration.md Specify the directory where the output diagram files should be saved. ```default pyreverse --output-directory ``` -------------------------------- ### Running Pyreverse Programmatically Source: https://github.com/pylint-dev/pylint/blob/main/doc/development_guide/api/index.md Shows how to use the pyreverse API to generate UML diagrams. ```APIDOC ## run_pyreverse ### Description Invokes the pyreverse tool to generate UML diagrams for Python code. ### Method Python function call ### Parameters - **arguments** (any) - Required - Arguments for pyreverse. (Specifics not detailed in source) ``` -------------------------------- ### Corrected Code with Full LF Line Endings Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/convention/mixed-line-endings.md This example shows code where all line endings are LF, resolving the C0327 warning. ```python print("Hello") # LF (\n) print("World") # LF (\n) ``` -------------------------------- ### Corrected Code with Full CRLF Line Endings Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/convention/mixed-line-endings.md This example shows code where all line endings are CRLF, resolving the C0327 warning. ```python print("Hello") # CRLF (\r\n) print("World") # CRLF (\r\n) ``` -------------------------------- ### Python Class With Docstring Example Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/convention/missing-class-docstring.md This snippet demonstrates the correct way to define a Python class with a docstring, satisfying the C0115 check. ```python class Person: """Class representing a person""" def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name ``` -------------------------------- ### Correct code: Implementing __enter__ and __exit__ Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/error/not-context-manager.md This code shows the correct implementation of a context manager by including both '__enter__' and '__exit__' methods. This satisfies the requirements for use in a 'with' statement. ```python class MyContextManager: def __enter__(self): pass def __exit__(self, *exc): pass with MyContextManager() as c: pass ``` -------------------------------- ### Pylint import-self Error Example Source: https://github.com/pylint-dev/pylint/blob/main/doc/data/messages/i/import-self/details.rst This code demonstrates the 'import-self' error. It occurs when a module imports a name that is defined within the same module. ```python from my_file import a_function # [import-self] def a_function(): pass ``` -------------------------------- ### Correct code implementing __eq__ and __hash__ Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/warning/eq-without-hash.md This code demonstrates the correct way to implement both __eq__ and __hash__ methods in a class to ensure proper hashing behavior. ```python class Fruit: def __init__(self) -> None: self.name = "apple" def __eq__(self, other: object) -> bool: return isinstance(other, Fruit) and other.name == self.name def __hash__(self) -> int: return hash(self.name) ``` -------------------------------- ### Initialize Dictionary with Known Key/Value Source: https://github.com/pylint-dev/pylint/blob/main/tests/functional/ext/dict_init_mutate.txt Declare all known key/values when initializing the dictionary. This helps in making the dictionary structure explicit from the start. ```python config = {'pwd': 'hello'} ``` ```python config = {'dir': 'bin', 'user': 'me', 'workers': 5} ``` ```python config = {'options': {}} ``` ```python settings = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7} ``` -------------------------------- ### Avoid using exec with user input Source: https://github.com/pylint-dev/pylint/blob/main/doc/user_guide/messages/warning/exec-used.md This example demonstrates problematic code using 'exec' with user-provided input, which is a security risk. It's generally advised to avoid this pattern. ```python username = "Ada" code_to_execute = f"""input('Enter code to be executed please, {username}: ')""" program = exec(code_to_execute) # [exec-used] exec(program) # [exec-used] ```