Apprendre à utiliser Pylint (2023)

Cet article est une introduction à la fibrePylint, un outil de vérification de code qui peut signaler des erreurs Python ainsi que des morceaux de code qui enfreignent un certain nombre de conventions. Cela permet d'éviter les erreurs et d'obtenir un code unique. Les règles que Pylint applique par défaut suivent le guide de style Python PEP 8https://www.python.org/dev/peps/pep-0008.L'application sera également présentée dans l'articlePylintligne de commande et son intégration avecStudio visuel de code.

Pour commenter le contenu de cet article, nous vous offrons un espace de dialogue sur le forumRemarque Apprendre à utiliser Pylint (2).

Numéro d'articletemps.

Deux auteurs

Jennifer Andersen

Michel Baron

Article

publié le25 juin 2020

Version PDFVersion hors ligne

ePub,Azwetmobile

Liens sociaux

I. Geler le logiciel

Pour effectuer les opérations décrites dans cet article, vous devez installer les outils suivants :

  • Python 3 ;
  • Pépin;
  • Kod Visual Studio (VSCode).

II. Assemblée

ZPépin, le programme d'installation classique du module python, l'installation est très simple grâce à la ligne de commande suivante :

Choisir

pip installer pylint

Vous pouvez vous assurer que l'outilpylintil s'installe en exécutant la ligne de commande suivante :

Choisir

1.
2.
3.
4.
5.
6.
7.
8.
9.
dix.

$ pip show pylintVersion : 2.5.2Samenvatting : vérificateur statique de code pythonAccueil : https://github.com/PyCQA/pylintAuteur : Python Code Quality AuthorityE-mail et autorité : code-quality@python.orgLicence : GPLEmplacement : /Users/USER/ Library/ Python/3.7/lib/python/site-packages Vereist : mccabe, isort, astroid, toml Vereist door :

Au moment de la rédaction, il s'agit de la version actuellepylintc'était la version 2.5.2.

(Video) TUTO D1- Python Linter son code avec flake8 et pylint Formation “ Qualité de code et

III. Utiliser

Ensuite, nous pouvons exécuterPylintdepuis la ligne de commande. Il est possible d'analyser le code d'un module ou d'un package Python entier (pour être considéré comme un package, un dossier doit avoir__init__.py).

Pour analyser le module :

Depuis:

Choisir

pylint direktorij/mon_module.py

Pour analyser tous les modules du package :

Choisir

pylint mon_paquet

Il est également possible de spécifier les modules que vous souhaitez analyser au lieu d'en sélectionner un seul. DONC,Pylintanalyse le ou les fichiers et répertorie toutes les règles où les règles ne sont pas suivies. Cependant, cette liste peut être très longue, il est donc possible de configurer les règles par rapport auxquelles ils doivent être vérifiésPylint.

IV. Configuration

Les règles qu'il imposePylintils sont divisés en cinq catégories différentes marquées d'une lettre, nous avons donc :

  • C :Convention: la convention de chiffrement n'est pas respectée ;
  • R :Refactoring: détection des mauvaises pratiques ;
  • W :Avertissement: pour les problèmes spécifiques à Python ;
  • MI:faux: pour détecter d'éventuelles erreurs dans le code ;
  • F:catastrophique: prévention des erreursPylintjogging.

Il existe trois façons de configurer les règles Pylint. Toutes les règles sont également répertoriées dans la documentationPylint:https://pylint.readthedocs.io/en/latest/technical_reference/features.html.

IV-A. Ligne de commande

La première consiste à activer ou désactiver des règles ou des catégories de règles directement depuis la ligne de commande. Par défaut, les règles sont activées et pour la désactivation, nous n'en exécutons que certaines :

Choisir

Module $ pylint --disable=

Par exemple:

(Video) APPRENDRE PYTHON [TUTO PROGRAMMATION COMPLET DÉBUTANT]

Choisir

$ pylint package/module.py --disable=fixme,invalid-name

Ou pour désactiver toutes les règles de convention (marquées d'un C) :

Choisir

$ pylint package/module.py --disable=C

Par contre, pour n'activer qu'un petit nombre de règles, on utilisera cette optiondésactiver = tout, puis activez-le et spécifiez les règles que vous souhaitez appliquer.

Choisir

$ module pylint --disable=sve --enable=

Cependant, cette méthode n'est pas très efficace, surtout lorsque vous voulez exécuterPylinttoujours dans les mêmes conditions. Il est donc possible de générer et de modifier un fichier de configuration.

IV-B. fichier de configuration

Générez un fichier de configuration :

Choisir

$ pylint --generiraj-rcfile >.pylintrc

Durée.pylintrcgénère alorsPylintdans le dossier courant. Il contient déjà certaines informations et paramètres et un ensemble de règles qui sont désactivées par défaut dans la section "GESTION DES MESSAGES" avec le paramètre "désactiver".

Vous pouvez ensuite désactiver ou réactiver les règles en ajoutant les règles que vous souhaitez désactiver à la liste ou en les supprimant de la liste existante. De plus, il existe une option pour définir des règles configurables. Par exemple, vous pouvez appliquer un nombre minimum de règles pour docstring (qui n'est pas appliqué par défaut car la valeur est -1) en modifiant la valeur du paramètre au niveau des règles suivantes :

Choisir

1.
2.
3.

(Video) How to use Pylint a code analysis for Python

# Longueur de ligne minimale pour les fonctions/classes qui en ont besoin# de documents, les plus courts sont exclus.longueur minimale de la séquence de documents=1

Vous pouvez également configurer la forme des noms que vous acceptez, comme exiger que les variables suivent la convention camlCase au lieu de snake_case. D'autres règles n'ont pas de paramètres, comme une règle qui nécessite un séparateur décimal.

Il est également possible de générer un fichier de configuration en spécifiant des options sur la ligne de commande pour l'intégrer dans le fichier.

Choisir

$ pylint --disable=C --docstring-min-length=2 --generate-rcfile

IV-C. Remarques

Les notes activent ou désactivent une ou plusieurs règles localement. Vous pouvez ajouter des notes ou des commentaires spécifiques à Pylint directement dans le code pour modifier les règles qui ne s'appliquent qu'à des blocs de code spécifiques. Pour activer ou désactiver la règle, nous allons écrire le code suivant :

Choisir

# pylint : disable=nom invalide, activer fixme=aucun membre

Ce commentaire doit être placé en fin de ligne pour que cette règle s'applique à une seule ligne. Pour appliquer une règle à un bloc entier, placez une annotation après la première règle qui définit le bloc (après la règlepokefonction pour l'appliquer à l'ensemble de la fonction, ligne par ligne ou ligne par ligneje, sachant quejeetAndersforment deux blocs distincts). Enfin, il peut être appliqué à l'ensemble du dossier en inscrivant cette note dans les premières lignes du dossier.

V. Intégration avec Visual Studio Code

UtiliserPylintzStudio visuel de code(Kod VSC), l'extension Python doit être installée. DEPUISStudio visuel de code(Kod VSC), ouvrez le menuRallongeset entrezPythondans le champ de saisie. Plusieurs options sont disponibles, choisissez une extension développée par Microsoft (généralement la première de la liste). Ensuite, vous devez vérifier que l'interpréteur Python est correctement configuré. Faites pour celaCTRL+MAJ+Ppuis entrez une valeurPython : Choisissez un interpréteurpuis assurez-vous que le traducteur est sélectionné correctement.

Généralement quandPylintest installé,Studio visuel de code(Kod VSC) en tient automatiquement comptePylint. Cependant, il ne vérifie qu'un petit nombre des règles qu'il proposePylint. Appliquer les mêmes règles àStudio visuel de codeCoPylinten ligne de commande, le plus simple est de générer un fichier de configuration (voir la section précédente). Ensuite, les règles sont vérifiées parStudio visuel de codeje pourPylintla ligne de commande sera la même.

Erreurs et messages dePylintils sont ensuite affichés en mettant en évidence les parties problématiques du code, ainsi que dans l'onglet "Problèmes" (voir image ci-dessous).

Des ajustements de paramètres peuvent être nécessaires pour s'assurer que cet écran est completKod VSC: Recherchez "Pylint" dans les paramètres et vérifiez le poids attribué à chaque catégoriePylint : si la gravité est "Advisory", alors les messages dePylintsera (presque) invisible, vous devrez donc choisir une sévérité différente pour tout ce qui doit être affiché.

TOI. Quelques ajouts intéressants

Standard,Pylintil ne vérifie pas la documentation et il ne vérifie pas qu'il suit correctement un ensemble de conventions. Nous pouvons pré-imposer sa présence en spécifiant un nombre minimum de lignes pour la documentation du tableau de documents.

Choisir

1.
2.
3.

(Video) Apprendre Python 41 - Styler son Code avec PEP8

# Longueur de ligne minimale pour les fonctions/classes qui en ont besoin# de documents, les plus courts sont exclus.longueur minimale de la séquence de documents=1

La vérification peut alors être appliquée à la documentation :https://docs.pylint.org/en/1.6.0/extensions.html#parameter-documentation-checker.A cet effet, nous ajoutons à la liste des pluginspylint.extensions.docparams. Vérifie si la documentation suit l'une des trois conventions Sphinx, Google ou Numpy.

Choisir

1.
2.
3.
4.

# Liste des plugins (si les valeurs sont séparées par des virgules python# noms de modules) à charger, généralement pour enregistrer des éléments supplémentaires# de disques.extras chargés=pylint.extensions.docparams

Cependant, cela ne vérifie que la documentation si elle existe, et ne vérifie les paramètres et les retours que s'ils sont au moins partiellement documentés. Pour assurer la présence de cette documentation, il est nécessaire d'ajouter les paramètres suivants dans la section [BASIC] :

Choisir

1.
2.
3.
4.
5.

[BASE]# Si nécessaire, forcer tous les éléments du tableau doc ​​à être présents accept-no-param-doc = nodocument acceptation-non-acceptation= neeacceptation-document-pas de remboursement= neeaccepter-aucun-résultat-tant que= nee

ALLER. Exemples

A titre d'exemple, ci-dessous se trouve le fichier de configuration qui a été généré automatiquement comme mentionné précédemment et qui a été modifié pour une version simplifiée.

Choisir

1.
2.
3.
4.
5.
6.
7.
8.
9.
dix.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.

[HÉBERGER]# Une liste de plugins (sous forme de valeurs séparées par des virgules des noms de module python) à charger,# généralement pour enregistrer des contrôleurs supplémentaires.extras chargés=pylint.extensions.docparams[NOUVELLESCONTRÔLER]# Désactiver tous les messages, puis uniquement les lignes critiques# et conventions de style de nommageÉteindre= toutembrayage=F, style de nommage d'argument, style de nommage attr, style de nommage de classe, style de nommage d'attribut de classe, style de nommage constant, style de nommage de fonction, style de nommage de variable linéaire, style de nommage de méthode, style de nommage de module, style de nommage de variable[BASE]# Force tous les éléments du tableau de document à être présents si nécessaire.ne pas accepter-param-doc= needocument acceptation-non-acceptation= neeacceptation-document-pas de remboursement= neeaccepter-aucun-résultat-tant que= nee# Longueur de ligne minimale réduite pour les fonctions/classes qui nécessitent des chaînes de document# est sorti.longueur minimale de la séquence de documents=1

VIII. Conclusion et remerciements

Cet article montre la mise en œuvre du linterPylint, à utiliser via la ligne de commande et l'intégration de l'éditeurStudio visuel de code. Nous vous avons également montré comment activer ou désactiver des politiques à l'aide d'une configuration temporaire (depuis la ligne de commande) ou d'une configuration permanente à l'aide d'un fichier de configuration.pylintrc.

Nous voulons vous remercierClaude'a Leloupapour sa correction orthographique.

Vous avez aimé ce tutoriel ? Partagez-le en cliquant sur les boutons suivants :

Les ressources présentées sur ce site sont gratuites et vous pouvez les utiliser à votre convenance. Cependant, la page de présentation est l'oeuvre intellectuelle de l'auteur. Copyright © 2020 Jennie Andersen. Aucune reproduction, même partielle, de cette page ou de l'intégralité de son contenu : textes, documents, images, etc. n'est autorisée sans l'autorisation expresse de l'auteur. Sinon, vous êtes légalement responsable jusqu'à trois ans de prison et jusqu'à 300 000 euros de dommages et intérêts.

(Video) Configurer Visual Studio Code pour Python

FAQs

How do I get rid of pylint warning? ›

This may be done by adding # pylint: disable=some-message,another-one at the desired block level or at the end of the desired line of code. 4.2 Is there a way to disable a message for a particular module only? You can disable messages by: numerical ID: E1101 , E1102 , etc.

What's a good pylint score? ›

Pylint. Run pylint on your code before checking in. New files shall have a Pylint score of 9 or higher. New files will not be accepted if they have a Pylint score lower than 9.

How useful is pylint? ›

PyLint can keep you from really really hard to find and complicated bugs. At worst, it can save you the time of a test run. At best, it can help you avoid complicated production mistakes.

How do I disable pylint on VsCode? ›

Fully disable the linting

To do so, type Command + Shift + P (or Ctrl + Shift + P on PC) in VsCode. This will open a command prompt at the top of the window. Then type the command Python: Enable Linting , and select off .

How do I ignore warnings warn in Python? ›

The warnings module is a built-in Python library that allows you to control the display of warning messages. To turn off warning messages, you can use the warnings. filterwarnings() function. For example, This will disable the display of all warning messages.

How do I disable specific warnings in compiler? ›

To turn off the warning for a specific line of code, use the warning pragma, #pragma warning(suppress : 4996) .

How do I disable pylint in a file? ›

If you want to disable specific warnings only, this can be done by adding a comment such as # pylint: disable=message-name to disable the specified message for the remainder of the file, or at least until # pylint: enable=message-name .

How to disable pylint in Python? ›

# Disable all Pylint warnings in a File

If you need to disable all Pylint warnings in a file, set the # pylint: skip-file comment at the top of the module. Copied! For example, Pylint won't report any of the warnings in the following file.

How does pylint work in Python? ›

Pylint is a static code checker, meaning it can analyse your code without actually running it. Pylint checks for errors, tries to enforce a coding standard, and tries to enforce a coding style.

How do I disable Pylint for a specific line? ›

you can ignore it by adding a comment in the format # pylint: disable=[problem-code] at the end of the line where [problem-code] is the value inside pylint(...) in the pylint message – for example, abstract-class-instantiated for the problem report listed above.

How do I remove warnings from VSCode? ›

The easiest way to remove red wavy error and warning underlines is by changing their color to a transparent HTML color in Visual Studio Code settings file (settings. json) Oof! Those red wavy error underlines can be annoying.

How do I suppress warnings in Visual Studio code? ›

You can suppress violations in code using a preprocessor directive, the #pragma warning (C#) or Disable (Visual Basic) directive to suppress the warning for only a specific line of code. Or, you can use the SuppressMessage attribute.

How do I output pylint to a text file? ›

The simplest way to output to a file is with the --output=<filename> option. The default format for the output is raw text. You can change this by passing pylint the --output-format=<value> option. Possible values are: text , json , parseable , colorized and msvs (for Visual Studio).

How do I use pylint in Vscode? ›

Linting Python in Visual Studio Code
  1. To enable linters, open the Command Palette (Ctrl+Shift+P) and select the Python: Select Linter command. ...
  2. You can easily toggle between enabling and disabling your linter. ...
  3. To perform linting, open the Command Palette (Ctrl+Shift+P), filter on "linting", and select Python: Run Linting.

Which Python version is pylint? ›

Pylint is a static code analyser for Python 2 or 3.

How do you bypass exceptions in Python? ›

In Python, you can ignore an exception and continue processing by using the "try... except" construct. If an exception occurs, the "except" block will be executed, and you can handle the exception accordingly. If you don't want to handle the exception, you can simply ignore it by using the "pass" keyword.

What are weak warnings in Python? ›

Weak Warning. : code fragments that can be improved or optimized (redundant code, duplicated code fragments, and so on). Server Problem. : problems that come from an external build server, for example, from TeamCity.

Why do we use warning in Python? ›

Warning messages are typically issued in situations where it is useful to alert the user of some condition in a program, where that condition (normally) doesn't warrant raising an exception and terminating the program. For example, one might want to issue a warning when a program uses an obsolete module.

How do you compile without warnings being treated as errors? ›

You can make all warnings being treated as such using -Wno-error. You can make specific warnings being treated as such by using -Wno-error=<warning name> where <warning name> is the name of the warning you don't want treated as an error. If you want to entirely disable all warnings, use -w (not recommended).

Can compiler warnings be ignored? ›

These are warnings. They are things that are obvious to a compiler, using all the strict rules of C++ at its disposal, that you might have overlooked. Turning warnings off, or ignoring them, is like choosing to ignore free advice from those more skilled than you.

How to ignore specific warning in GCC? ›

To answer your question about disabling specific warnings in GCC, you can enable specific warnings in GCC with -Wxxxx and disable them with -Wno-xxxx. From the GCC Warning Options: You can request many specific warnings with options beginning -W , for example -Wimplicit to request warnings on implicit declarations.

How do I ignore a folder in pylint? ›

You can not give a path, but only the "basename" of the directory. E.g., use --ignore=lib instead of --ignore-=appengine-toolkit/gaetk/lib . The problem is you will ignore all directories named lib .

How do I disable pylint C0103? ›

I temporarily already managed to disable it in Sublime by going to "Preferences > Package Settings > Sublime Linter > Settings - User" and adding "disable": "C0103" to pylint block.

How do I disable too few public methods? ›

Probably a better way to disable this is to set min-public-methods=0 in the [BASIC] section of the config file.

What is linting in Python? ›

Linting is a process for identifying bugs and stylistic errors in your code. The process is carried out by analysis tools called 'linters', which are widely available for every major programming language. Linters will flag issues and style violations in your code, sort of like a spell checker!

How do I create a Pylintrc file? ›

  1. or straight up just: pylint --generate-rcfile > .pylintrc. – Mahrkeenerh. ...
  2. With all due respect, this is just a generic Windows file creation command. ...
  3. If you want to create on Windows File Explorer a dot prefixed file named ".pylintrc", you need to type ".pylintrc." (use a trailing dot).
Mar 17, 2014

How to install pylint in Python? ›

Installing Pylint (Maya 2017-2020)
  1. Open a Command Prompt or Terminal. On Windows, navigate to the Python root directory (install location)
  2. Run the following command: python -m pip install pylint.
  3. Note the location of the pylint executable: Windows - pylint.exe should be in the Scripts folder (Python root directory)

What is the difference between Sonarlint and pylint? ›

Sonarlint is a code linter and pylint is too. I haven't used sonarlint, but it seems that analyzes the code a bit deeper that pylint does. From my experience, pylint only follows a set of rules (that you can modify, by the way), while sonarlint goes a bit further analyzing the inner workings of your code.

What are the different types of messages in pylint? ›

The message type can be:
  • [R]efactor for a “good practice” metric violation.
  • [C]onvention for coding standard violation.
  • [W]arning for stylistic problems, or minor programming issues.
  • [E]rror for important programming issues (i.e. most probably bug)
  • [F]atal for errors which prevented further processing.

How do I disable E501 line too long? ›

The E501 line too long error comes from pep8, not pylint. You can run it as pep8 --ignore=E501 to avoid that report (specially if you are already checking long lines with pylint).

How do I get rid of the blue lines in VS Code? ›

Press command+shift+p (open command pallete) Then type Disable Error Squiggles. And click on that Disable Error Squiggles.

How do I remove code insiders? ›

Mac. GUI Based: Open Finder -> Applications. Right click "Visual Studio Code - Insiders. app" and move it to the trash.

What is pragma warning disable? ›

Remarks
warning-specifierMeaning
disableDon't issue the specified warning messages.
errorReport the specified warnings as errors.
onceDisplay the specified message(s) only one time.
3 more rows
Jan 24, 2023

How to hide warnings in R script? ›

To temporarily suppress warnings in global settings and turn them back on, use the following code:
  1. defaultW <- getOption("warn")
  2. options(warn = -1)
  3. [YOUR CODE]
  4. options(warn = defaultW)

How to disable compiler warning in Visual Studio command line? ›

To turn off the warning without code changes

You can turn off the warning for a specific line of code by using the warning pragma, #pragma warning(suppress : 4698) . You can also turn off the warning within a file by using the warning pragma, #pragma warning(disable : 4698) .

How to disable warning in gcc? ›

The warning is emitted only with --coverage enabled. By default, this warning is enabled and is treated as an error. -Wno-coverage-invalid-line-number can be used to disable the warning or -Wno-error=coverage-invalid-line-number can be used to disable the error.

How do I remove warnings from VS code? ›

The easiest way to remove red wavy error and warning underlines is by changing their color to a transparent HTML color in Visual Studio Code settings file (settings. json) Oof! Those red wavy error underlines can be annoying.

How do you ignore pylint in a function? ›

you can ignore it by adding a comment in the format # pylint: disable=[problem-code] at the end of the line where [problem-code] is the value inside pylint(...) in the pylint message – for example, abstract-class-instantiated for the problem report listed above.

Can I ignore warning messages from my compiler? ›

Warnings must not be ignored.

How do I ignore a warning node? ›

After some research I noticed that there are generally 2 ways to disable the warnings:
  1. set environmental variable NODE_NO_WARNINGS=1.
  2. call the script with node --no-warnings ./index. js.
Apr 20, 2019

How do I ignore all errors in GCC? ›

Use "-w" to ignore all warnings. You can't ignore errors. The long answer: https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html, which has information on all the warning/error options.

How to suppress all warnings in C#? ›

Use a #pragma warning (C#) or Disable (Visual Basic) directive to suppress the warning for only a specific line of code.

How do I use Pylint in VS Code? ›

Linting Python in Visual Studio Code
  1. To enable linters, open the Command Palette (Ctrl+Shift+P) and select the Python: Select Linter command. ...
  2. You can easily toggle between enabling and disabling your linter. ...
  3. To perform linting, open the Command Palette (Ctrl+Shift+P), filter on "linting", and select Python: Run Linting.

How do I turn off JavaScript warnings in Visual Studio? ›

Option 1: Options > JS Errors
  1. Open Tools > Options.
  2. Navigate to Text Editor > JavaScript/TypeScript > Code Validation.
  3. Set Enable JavaScript errors to false.
  4. or, set Enable JavaScript errors to true and Show errors as warnings to true.
Mar 10, 2017

What is Pragma warning disable? ›

Remarks
warning-specifierMeaning
disableDon't issue the specified warning messages.
errorReport the specified warnings as errors.
onceDisplay the specified message(s) only one time.
3 more rows
Jan 24, 2023

Videos

1. Invite de Commande Windows - Tutoriel Complet
(MaxCode)
2. [Tips] - Solve 'pip' is not recognized as an internal command on Windows 10
(Foxxpy - Mathématiques et algorithmie)
3. Tutoriel 03 - Formation Python - Prise en main
(BalacSoft)
4. Installation & Configuration de l'IDE Wing Python
(Très Facile !)
5. TUTO Python / PySide / Qt : Deux approches distinctes de Qt
(Dominique Liard)
6. Functions from zero
(Pragmatic AI Labs)
Top Articles
Latest Posts
Article information

Author: Fredrick Kertzmann

Last Updated: 06/13/2023

Views: 5277

Rating: 4.6 / 5 (66 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Fredrick Kertzmann

Birthday: 2000-04-29

Address: Apt. 203 613 Huels Gateway, Ralphtown, LA 40204

Phone: +2135150832870

Job: Regional Design Producer

Hobby: Nordic skating, Lacemaking, Mountain biking, Rowing, Gardening, Water sports, role-playing games

Introduction: My name is Fredrick Kertzmann, I am a gleaming, encouraging, inexpensive, thankful, tender, quaint, precious person who loves writing and wants to share my knowledge and understanding with you.