0
# Configuration Management
1
2
Hierarchical configuration system that handles command-line arguments, configuration files, and programmatic settings. Pylint's flexible configuration allows customization of analysis behavior, message filtering, and output formatting to match project requirements and coding standards.
3
4
## Capabilities
5
6
### Configuration File Discovery
7
8
Functions for locating and loading configuration files from multiple sources.
9
10
```python { .api }
11
def find_default_config_files():
12
"""
13
Locate default configuration files.
14
15
Searches for configuration files in standard locations:
16
- Current directory: .pylintrc, pylintrc, pyproject.toml, setup.cfg
17
- User home directory: ~/.pylintrc
18
- System directories: /etc/pylintrc
19
20
Returns:
21
list: Paths to found configuration files
22
"""
23
24
def find_pylintrc():
25
"""
26
Find pylintrc configuration file.
27
28
Searches in order of precedence:
29
1. PYLINTRC environment variable
30
2. Current directory .pylintrc
31
3. Parent directories (walking up)
32
4. User home ~/.pylintrc
33
5. System /etc/pylintrc
34
35
Returns:
36
str: Path to pylintrc file or None
37
"""
38
```
39
40
### Configuration File Processing
41
42
Functions for reading and parsing configuration from various file formats.
43
44
```python { .api }
45
def read_config_file(config_file, verbose=False):
46
"""
47
Read configuration from file.
48
49
Supports multiple configuration file formats:
50
- .pylintrc (INI format)
51
- pyproject.toml (TOML format)
52
- setup.cfg (INI format)
53
54
Args:
55
config_file (str): Path to configuration file
56
verbose (bool): Enable verbose output
57
58
Returns:
59
dict: Parsed configuration options
60
"""
61
```
62
63
### Arguments Management
64
65
Classes for handling command-line arguments and configuration options.
66
67
```python { .api }
68
class ArgumentsManager:
69
"""
70
Command-line argument management.
71
72
Handles parsing, validation, and processing of command-line
73
arguments and configuration file options.
74
"""
75
76
def __init__(self, prog, description):
77
"""
78
Initialize arguments manager.
79
80
Args:
81
prog (str): Program name
82
description (str): Program description
83
"""
84
85
def add_optik_option(self, *args, **kwargs):
86
"""
87
Add command-line option.
88
89
Args:
90
*args: Option names (e.g., '--disable', '-d')
91
**kwargs: Option configuration
92
"""
93
94
def register_options_provider(self, provider, own_group=True):
95
"""
96
Register options provider.
97
98
Args:
99
provider: Object providing configuration options
100
own_group (bool): Create separate option group
101
"""
102
103
def load_config_file(self):
104
"""Load configuration from file."""
105
106
def load_command_line_configuration(self, args=None):
107
"""
108
Load configuration from command line.
109
110
Args:
111
args (list): Command line arguments
112
"""
113
114
class ArgumentsProvider:
115
"""
116
Base class for configuration providers.
117
118
Provides interface for objects that contribute
119
configuration options to the argument manager.
120
"""
121
122
name: str # Provider name
123
options: tuple # Configuration options
124
priority: int # Loading priority
125
126
def load_defaults(self):
127
"""Load default option values."""
128
129
def option_value(self, opt):
130
"""
131
Get option value.
132
133
Args:
134
opt (str): Option name
135
136
Returns:
137
Option value
138
"""
139
```
140
141
### Configuration Initialization
142
143
Functions for initializing and setting up the complete configuration system.
144
145
```python { .api }
146
def _config_initialization(linter, args_list, reporter=None, config_file=None):
147
"""
148
Initialize configuration system.
149
150
Handles the complete configuration initialization process:
151
1. Load configuration files
152
2. Process command-line arguments
153
3. Set up reporters
154
4. Validate configuration
155
156
Args:
157
linter: PyLinter instance
158
args_list (list): Command-line arguments
159
reporter: Custom reporter instance
160
config_file (str): Specific configuration file path
161
"""
162
```
163
164
## Configuration File Formats
165
166
### .pylintrc Format
167
168
```ini
169
[MAIN]
170
# Python code to execute, usually for sys.path manipulation
171
init-hook=
172
173
# Files or directories to be skipped
174
ignore=tests,docs
175
176
# Regexp for files/directories to be skipped
177
ignore-patterns=
178
179
# Use multiple processes to speed up Pylint
180
jobs=1
181
182
# List of plugins to load
183
load-plugins=
184
185
# Discover python modules and packages in the file system subtree
186
recursive=no
187
188
[MESSAGES CONTROL]
189
# Only show warnings with the listed confidence levels
190
confidence=
191
192
# Disable the message, report, category or checker
193
disable=missing-docstring,
194
invalid-name
195
196
# Enable the message, report, category or checker
197
enable=c-extension-no-member
198
199
[REPORTS]
200
# Set the output format
201
output-format=text
202
203
# Include message's id in output
204
include-ids=no
205
206
# Template for displaying messages
207
msg-template={path}:{line}: [{msg_id}({symbol}), {obj}] {msg}
208
209
# Set the cache size for astroid objects
210
extension-pkg-whitelist=
211
212
[REFACTORING]
213
# Maximum number of nested blocks for function/method body
214
max-nested-blocks=5
215
216
# Complete name of functions that never returns
217
never-returning-functions=sys.exit
218
219
[BASIC]
220
# Naming style matching correct argument names
221
argument-naming-style=snake_case
222
223
# Regular expression matching correct argument names
224
argument-rgx=[a-z_][a-z0-9_]{2,30}$
225
226
# Naming style matching correct variable names
227
variable-naming-style=snake_case
228
229
# Good variable names which should always be accepted
230
good-names=i,j,k,ex,Run,_
231
232
# Bad variable names which should always be refused
233
bad-names=foo,bar,baz,toto,tutu,tata
234
235
[FORMAT]
236
# Maximum number of characters on a single line
237
max-line-length=100
238
239
# Maximum number of lines in a module
240
max-module-lines=1000
241
242
# String used as indentation unit
243
indent-string=' '
244
245
# Expected format of line ending
246
expected-line-ending-format=
247
248
[LOGGING]
249
# Format style used to check logging format string
250
logging-format-style=old
251
252
# Logging modules to check that the string format arguments are in logging function parameter format
253
logging-modules=logging
254
255
[MISCELLANEOUS]
256
# List of note tags to take in consideration
257
notes=FIXME,XXX,TODO
258
259
[SIMILARITIES]
260
# Minimum lines number of a similarity
261
min-similarity-lines=4
262
263
# Ignore comments when computing similarities
264
ignore-comments=yes
265
266
# Ignore docstrings when computing similarities
267
ignore-docstrings=yes
268
269
# Ignore imports when computing similarities
270
ignore-imports=no
271
272
[SPELLING]
273
# Spelling dictionary name
274
spelling-dict=
275
276
# List of comma separated words that should not be checked
277
spelling-ignore-words=
278
279
# A path to a file that contains private dictionary
280
spelling-private-dict-file=
281
282
# Tells whether to store unknown words to indicated private dictionary
283
spelling-store-unknown-words=no
284
285
[TYPECHECK]
286
# List of decorators that produce context managers
287
contextmanager-decorators=contextlib.contextmanager
288
289
# List of members which are set dynamically and missed by pylint inference system
290
generated-members=
291
292
# Tells whether missing members accessed in mixin class should be ignored
293
ignore-mixin-members=yes
294
295
# List of module names for which member attributes should not be checked
296
ignored-modules=
297
298
# List of class names for which member attributes should not be checked
299
ignored-classes=optparse.Values,thread._local,_thread._local
300
301
# List of classes names for which member attributes should not be checked
302
ignored-classes=optparse.Values,thread._local,_thread._local
303
304
[VARIABLES]
305
# List of additional names supposed to be defined in builtins
306
additional-builtins=
307
308
# Tells whether unused global variables should be treated as a violation
309
allow-global-unused-variables=yes
310
311
# List of strings which can identify a callback function by name
312
callbacks=cb_,_cb
313
314
# A regular expression matching the name of dummy variables
315
dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
316
317
# Argument names that match this expression will be ignored
318
ignored-argument-names=_.*|^ignored_|^unused_
319
320
# Tells whether we should check for unused import in __init__ files
321
init-import=no
322
323
# List of qualified module names which can have objects that can redefine builtins
324
redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
325
326
[CLASSES]
327
# List of method names used to declare (i.e. assign) instance attributes
328
defining-attr-methods=__init__,__new__,setUp,__post_init__
329
330
# List of member names, which should be excluded from the protected access warning
331
exclude-protected=_asdict,_fields,_replace,_source,_make
332
333
# List of valid names for the first argument in a class method
334
valid-classmethod-first-arg=cls
335
336
# List of valid names for the first argument in a metaclass class method
337
valid-metaclass-classmethod-first-arg=cls
338
339
[DESIGN]
340
# Maximum number of arguments for function/method
341
max-args=5
342
343
# Maximum number of attributes for a class
344
max-attributes=7
345
346
# Maximum number of boolean expressions in an if statement
347
max-bool-expr=5
348
349
# Maximum number of branch for function/method body
350
max-branches=12
351
352
# Maximum number of locals for function/method body
353
max-locals=15
354
355
# Maximum number of parents for a class
356
max-parents=7
357
358
# Maximum number of public methods for a class
359
max-public-methods=20
360
361
# Maximum number of return/yield for function/method body
362
max-returns=6
363
364
# Maximum number of statements in function/method body
365
max-statements=50
366
367
# Minimum number of public methods for a class
368
min-public-methods=2
369
370
[IMPORTS]
371
# List of modules that can be imported at any level, not just the top level
372
allow-any-import-level=
373
374
# Allow wildcard imports from modules that define __all__
375
allow-wildcard-with-all=no
376
377
# Analyse import fallback blocks
378
analyse-fallback-blocks=no
379
380
# Deprecated modules which should not be used
381
deprecated-modules=optparse,tkinter.tix
382
383
# Create a graph of external dependencies in the given file
384
ext-import-graph=
385
386
# Create a graph of every (i.e. internal and external) dependencies in the given file
387
import-graph=
388
389
# Create a graph of internal dependencies in the given file
390
int-import-graph=
391
392
# Force import order to recognize a module as part of the standard compatibility libraries
393
known-standard-library=
394
395
# Force import order to recognize a module as part of a third party library
396
known-third-party=enchant
397
398
# Couples of modules and preferred modules
399
preferred-modules=
400
401
[EXCEPTIONS]
402
# Exceptions that will emit a warning when being caught
403
overgeneral-exceptions=BaseException,Exception
404
```
405
406
### pyproject.toml Format
407
408
```toml
409
[tool.pylint.main]
410
# Files or directories to be skipped
411
ignore = ["tests", "docs"]
412
413
# Use multiple processes to speed up Pylint
414
jobs = 0
415
416
# List of plugins to load
417
load-plugins = [
418
"pylint.extensions.docparams",
419
"pylint.extensions.mccabe"
420
]
421
422
[tool.pylint.messages_control]
423
# Disable the message, report, category or checker
424
disable = [
425
"missing-docstring",
426
"invalid-name",
427
"too-few-public-methods"
428
]
429
430
[tool.pylint.format]
431
# Maximum number of characters on a single line
432
max-line-length = 100
433
434
[tool.pylint.basic]
435
# Good variable names which should always be accepted
436
good-names = ["i", "j", "k", "ex", "Run", "_"]
437
438
[tool.pylint.design]
439
# Maximum number of arguments for function/method
440
max-args = 5
441
442
# Maximum number of locals for function/method body
443
max-locals = 15
444
```
445
446
## Programmatic Configuration
447
448
### Using PyLinter Configuration
449
450
```python
451
from pylint.lint import PyLinter
452
453
# Create linter instance
454
linter = PyLinter()
455
456
# Set basic options
457
linter.config.disable = ['missing-docstring', 'invalid-name']
458
linter.config.max_line_length = 120
459
linter.config.good_names = ['i', 'j', 'k', 'x', 'y', 'z']
460
461
# Configure reports
462
linter.config.reports = True
463
linter.config.score = True
464
linter.config.msg_template = '{path}:{line}: {msg_id}: {msg}'
465
466
# Configure analysis behavior
467
linter.config.recursive = True
468
linter.config.jobs = 4
469
linter.config.suggestion_mode = True
470
```
471
472
### Dynamic Configuration Loading
473
474
```python
475
from pylint.config import find_pylintrc, read_config_file
476
477
# Find configuration file
478
config_file = find_pylintrc()
479
if config_file:
480
# Load configuration
481
config = read_config_file(config_file, verbose=True)
482
483
# Apply to linter
484
linter = PyLinter()
485
linter.load_config_file(config_file)
486
```
487
488
### Custom Configuration Provider
489
490
```python
491
from pylint.config import ArgumentsProvider
492
493
class CustomConfigProvider(ArgumentsProvider):
494
"""Custom configuration provider."""
495
496
name = 'custom'
497
priority = 1
498
499
options = (
500
('custom-option', {
501
'default': True,
502
'type': 'yn',
503
'help': 'Enable custom behavior'
504
}),
505
('custom-threshold', {
506
'default': 10,
507
'type': 'int',
508
'help': 'Custom threshold value'
509
})
510
)
511
512
def load_defaults(self):
513
"""Load default values."""
514
for option_name, option_dict in self.options:
515
setattr(self.config, option_name.replace('-', '_'),
516
option_dict['default'])
517
518
# Register with linter
519
linter = PyLinter()
520
provider = CustomConfigProvider()
521
linter.register_options_provider(provider)
522
```
523
524
## Environment Variables
525
526
### Configuration Environment Variables
527
528
```bash
529
# Specify configuration file
530
export PYLINTRC=/path/to/custom/pylintrc
531
532
# Set default options
533
export PYLINT_DISABLE=missing-docstring,invalid-name
534
export PYLINT_JOBS=4
535
536
# Plugin loading
537
export PYLINT_LOAD_PLUGINS=mccabe,docparams
538
```
539
540
### Usage in Scripts
541
542
```python
543
import os
544
from pylint.lint import PyLinter
545
546
# Check environment variables
547
config_file = os.environ.get('PYLINTRC')
548
jobs = int(os.environ.get('PYLINT_JOBS', '1'))
549
disabled = os.environ.get('PYLINT_DISABLE', '').split(',')
550
551
linter = PyLinter()
552
if config_file:
553
linter.load_config_file(config_file)
554
555
linter.config.jobs = jobs
556
if disabled and disabled[0]: # Check if not empty
557
linter.config.disable.extend(disabled)
558
```
559
560
## Configuration Best Practices
561
562
### Project-Specific Configuration
563
564
```python
565
# Create project-specific .pylintrc
566
def create_project_config():
567
config_content = """
568
[MAIN]
569
init-hook='import sys; sys.path.append("src")'
570
load-plugins=pylint.extensions.mccabe
571
572
[MESSAGES CONTROL]
573
disable=missing-docstring,
574
invalid-name,
575
too-few-public-methods
576
577
[FORMAT]
578
max-line-length=100
579
indent-string=' '
580
581
[DESIGN]
582
max-args=7
583
max-locals=20
584
max-complexity=10
585
"""
586
587
with open('.pylintrc', 'w') as f:
588
f.write(config_content.strip())
589
590
# Use in CI/CD
591
def setup_ci_config():
592
linter = PyLinter()
593
594
# Strict settings for CI
595
linter.config.fail_under = 8.0 # Minimum score
596
linter.config.disable = ['locally-disabled'] # No local disables
597
linter.config.output_format = 'json' # Machine readable
598
599
return linter
600
```