• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

pyta-uoft / pyta / 13359480406

16 Feb 2025 10:38PM UTC coverage: 92.925% (+0.004%) from 92.921%
13359480406

Pull #1145

github

web-flow
Merge 52800060c into ee811eccb
Pull Request #1145: Add autoformat utility class and autoformat-options

2 of 2 new or added lines in 1 file covered. (100.0%)

6 existing lines in 1 file now uncovered.

3244 of 3491 relevant lines covered (92.92%)

17.65 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.71
/python_ta/__init__.py
1
"""Python Teaching Assistant
2

3
The goal of this module is to provide automated feedback to students in our
4
introductory Python courses, using static analysis of their code.
5

6
To run the checker, call the check function on the name of the module to check.
7

8
> import python_ta
9
> python_ta.check_all('mymodule.py')
10

11
Or, put the following code in your Python module:
12

13
if __name__ == '__main__':
14
    import python_ta
15
    python_ta.check_all()
16
"""
17

18
from __future__ import annotations
20✔
19

20
__version__ = "2.9.3.dev"  # Version number
20✔
21
# First, remove underscore from builtins if it has been bound in the REPL.
22
# Must appear before other imports from pylint/python_ta.
23
import builtins
20✔
24
import subprocess
20✔
25

26
try:
20✔
27
    del builtins._
20✔
28
except AttributeError:
20✔
29
    pass
20✔
30

31

32
import importlib.util
20✔
33
import logging
20✔
34
import os
20✔
35
import sys
20✔
36
import tokenize
20✔
37
import webbrowser
20✔
38
from builtins import FileNotFoundError
20✔
39
from os import listdir
20✔
40
from typing import Any, AnyStr, Generator, Optional, TextIO, Union
20✔
41

42
import pylint.config
20✔
43
import pylint.lint
20✔
44
import pylint.utils
20✔
45
from astroid import MANAGER, modutils
20✔
46
from pylint.lint import PyLinter
20✔
47
from pylint.utils.pragma_parser import OPTION_PO
20✔
48

49
from .config import (
20✔
50
    find_local_config,
51
    load_config,
52
    load_messages_config,
53
    override_config,
54
)
55
from .patches import patch_all
20✔
56
from .reporters import REPORTERS
20✔
57
from .reporters.core import PythonTaReporter
20✔
58
from .upload import upload_to_server
20✔
59
from .util.autoformat import Autoformatter
20✔
60

61
HELP_URL = "http://www.cs.toronto.edu/~david/pyta/checkers/index.html"
20✔
62

63

64
# Flag to determine if we've previously patched pylint
65
PYLINT_PATCHED = False
20✔
66

67

68
def check_errors(
20✔
69
    module_name: Union[list[str], str] = "",
70
    config: Union[dict[str, Any], str] = "",
71
    output: Optional[str] = None,
72
    load_default_config: bool = True,
73
    autoformat: Optional[bool] = False,
74
) -> PythonTaReporter:
75
    """Check a module for errors, printing a report."""
76
    return _check(
×
77
        module_name=module_name,
78
        level="error",
79
        local_config=config,
80
        output=output,
81
        load_default_config=load_default_config,
82
        autoformat=autoformat,
83
    )
84

85

86
def check_all(
20✔
87
    module_name: Union[list[str], str] = "",
88
    config: Union[dict[str, Any], str] = "",
89
    output: Optional[str] = None,
90
    load_default_config: bool = True,
91
    autoformat: Optional[bool] = False,
92
) -> PythonTaReporter:
93
    """Analyse one or more Python modules for code issues and display the results.
94

95
    Args:
96
        module_name:
97
            If an empty string (default), the module where this function is called is checked.
98
            If a non-empty string, it is interpreted as a path to a single Python module or a
99
            directory containing Python modules. If the latter, all Python modules in the directory
100
            are checked.
101
            If a list of strings, each string is interpreted as a path to a module or directory,
102
            and all modules across all paths are checked.
103
        config:
104
            If a string, a path to a configuration file to use.
105
            If a dictionary, a map of configuration options (each key is the name of an option).
106
        output:
107
            If provided, the PythonTA report is written to this path. Otherwise, the report
108
            is written to standard out or automatically displayed in a web browser, depending
109
            on which reporter is used.
110
        load_default_config:
111
            If True (default), additional configuration passed with the ``config`` option is
112
            merged with the default PythonTA configuration file.
113
            If False, the default PythonTA configuration is not used.
114
        autoformat:
115
            If True, autoformat all modules using the black formatting tool before analyzing code.
116

117
    Returns:
118
        The ``PythonTaReporter`` object that generated the report.
119
    """
120
    return _check(
20✔
121
        module_name=module_name,
122
        level="all",
123
        local_config=config,
124
        output=output,
125
        load_default_config=load_default_config,
126
        autoformat=autoformat,
127
    )
128

129

130
def _check(
20✔
131
    module_name: Union[list[str], str] = "",
132
    level: str = "all",
133
    local_config: Union[dict[str, Any], str] = "",
134
    output: Optional[str] = None,
135
    load_default_config: bool = True,
136
    autoformat: Optional[bool] = False,
137
) -> PythonTaReporter:
138
    """Check a module for problems, printing a report.
139

140
    The `module_name` can take several inputs:
141
      - string of a directory, or file to check (`.py` extension optional).
142
      - list of strings of directories or files -- can have multiple.
143
      - no argument -- checks the python file containing the function call.
144
    `level` is used to specify which checks should be made.
145
    `local_config` is a dict of config options or string (config file name).
146
    `output` is an absolute or relative path to capture pyta data output. If None, stdout is used.
147
    `load_default_config` is used to specify whether to load the default .pylintrc file that comes
148
    with PythonTA. It will load it by default.
149
    `autoformat` is used to specify whether the black formatting tool is run. It is not run by default.
150
    """
151
    # Configuring logger
152
    logging.basicConfig(format="[%(levelname)s] %(message)s", level=logging.NOTSET)
20✔
153

154
    linter = reset_linter(config=local_config, load_default_config=load_default_config)
20✔
155
    current_reporter = linter.reporter
20✔
156
    current_reporter.set_output(output)
20✔
157
    messages_config_path = linter.config.messages_config_path
20✔
158
    messages_config_default_path = linter._option_dicts["messages-config-path"]["default"]
20✔
159
    use_pyta_error_messages = linter.config.use_pyta_error_messages
20✔
160
    messages_config = load_messages_config(
20✔
161
        messages_config_path, messages_config_default_path, use_pyta_error_messages
162
    )
163

164
    global PYLINT_PATCHED
165
    if not PYLINT_PATCHED:
20✔
166
        patch_all(
20✔
167
            messages_config, linter.config.z3
168
        )  # Monkeypatch pylint (override certain methods)
169
        PYLINT_PATCHED = True
20✔
170

171
    # Try to check file, issue error message for invalid files.
172
    try:
20✔
173
        # Flag indicating whether at least one file has been checked
174
        is_any_file_checked = False
20✔
175

176
        for locations in _get_valid_files_to_check(module_name):
20✔
177
            f_paths = []  # Paths to files for data submission
20✔
178
            errs = []  # Errors caught in files for data submission
20✔
179
            config = {}  # Configuration settings for data submission
20✔
180
            for file_py in get_file_paths(locations):
20✔
181
                allowed_pylint = linter.config.allow_pylint_comments
20✔
182
                if not _verify_pre_check(file_py, allowed_pylint):
20✔
183
                    continue  # Check the other files
×
184
                # Load config file in user location. Construct new linter each
185
                # time, so config options don't bleed to unintended files.
186
                # Reuse the same reporter each time to accumulate the results across different files.
187
                linter = reset_linter(
20✔
188
                    config=local_config,
189
                    file_linted=file_py,
190
                    load_default_config=load_default_config,
191
                )
192

193
                if autoformat:
20✔
194
                    autoformatter = Autoformatter(
20✔
195
                        linter.config.autoformat_options, linter.config.max_line_length
196
                    )
197
                    autoformatter.run(file_py)
20✔
198

199
                if not is_any_file_checked:
20✔
200
                    prev_output = current_reporter.out
20✔
201
                    current_reporter = linter.reporter
20✔
202
                    current_reporter.out = prev_output
20✔
203

204
                    # At this point, the only possible errors are those from parsing the config file
205
                    # so print them, if there are any.
206
                    if current_reporter.messages:
20✔
207
                        current_reporter.print_messages()
20✔
208
                else:
209
                    linter.set_reporter(current_reporter)
20✔
210

211
                # The current file was checked so update the flag
212
                is_any_file_checked = True
20✔
213

214
                module_name = os.path.splitext(os.path.basename(file_py))[0]
20✔
215
                if module_name in MANAGER.astroid_cache:  # Remove module from astroid cache
20✔
216
                    del MANAGER.astroid_cache[module_name]
20✔
217
                linter.check([file_py])  # Lint !
20✔
218
                current_reporter.print_messages(level)
20✔
219
                if linter.config.pyta_file_permission:
20✔
UNCOV
220
                    f_paths.append(file_py)  # Appending paths for upload
×
221
                logging.info(
20✔
222
                    "File: {} was checked using the configuration file: {}".format(
223
                        file_py, linter.config_file
224
                    )
225
                )
226
                logging.info(
20✔
227
                    "File: {} was checked using the messages-config file: {}".format(
228
                        file_py, messages_config_path
229
                    )
230
                )
231
            if linter.config.pyta_error_permission:
20✔
UNCOV
232
                errs = list(current_reporter.messages.values())
×
233
            if (
20✔
234
                f_paths != [] or errs != []
235
            ):  # Only call upload_to_server() if there's something to upload
236
                # Checks if default configuration was used without changing options through the local_config argument
237
                if linter.config_file[-19:-10] != "python_ta" or local_config != "":
×
238
                    config = linter.config.__dict__
×
UNCOV
239
                upload_to_server(
×
240
                    errors=errs,
241
                    paths=f_paths,
242
                    config=config,
243
                    url=linter.config.pyta_server_address,
244
                    version=__version__,
245
                )
246
        # Only generate reports (display the webpage) if there were valid files to check
247
        if is_any_file_checked:
20✔
248
            linter.generate_reports()
20✔
249
        return current_reporter
20✔
250
    except Exception as e:
20✔
251
        logging.error(
20✔
252
            "Unexpected error encountered! Please report this to your instructor (and attach the code that caused the error)."
253
        )
254
        logging.error('Error message: "{}"'.format(e))
20✔
255
        raise e
20✔
256

257

258
def reset_linter(
20✔
259
    config: Optional[Union[dict, str]] = None,
260
    file_linted: Optional[AnyStr] = None,
261
    load_default_config: bool = True,
262
) -> PyLinter:
263
    """Construct a new linter. Register config and checker plugins.
264

265
    To determine which configuration to use:
266
    - If the option is enabled, load the default PythonTA config file,
267
    - If the config argument is a string, use the config found at that location,
268
    - Otherwise,
269
        - Try to use the config file at directory of the file being linted,
270
        - If the config argument is a dictionary, apply those options afterward.
271
    Do not re-use a linter object. Returns a new linter.
272
    """
273

274
    # Tuple of custom options. Note: 'type' must map to a value equal a key in the pylint/config/option.py `VALIDATORS` dict.
275
    new_checker_options = (
20✔
276
        (
277
            "server-port",
278
            {
279
                "default": 0,
280
                "type": "int",
281
                "metavar": "<port>",
282
                "help": "Port number for the HTML report server",
283
            },
284
        ),
285
        (
286
            "watch",
287
            {
288
                "default": False,
289
                "type": "yn",
290
                "metavar": "<yn>",
291
                "help": "Run the HTML report server in persistent mode",
292
            },
293
        ),
294
        (
295
            "pyta-number-of-messages",
296
            {
297
                "default": 0,  # If the value is 0, all messages are displayed.
298
                "type": "int",
299
                "metavar": "<number_messages>",
300
                "help": "The maximum number of occurrences of each check to report.",
301
            },
302
        ),
303
        (
304
            "pyta-template-file",
305
            {
306
                "default": "",
307
                "type": "string",
308
                "metavar": "<pyta_reporter>",
309
                "help": "HTML template file for the HTMLReporter.",
310
            },
311
        ),
312
        (
313
            "pyta-error-permission",
314
            {
315
                "default": False,
316
                "type": "yn",
317
                "metavar": "<yn>",
318
                "help": "Permission to anonymously submit errors",
319
            },
320
        ),
321
        (
322
            "pyta-file-permission",
323
            {
324
                "default": False,
325
                "type": "yn",
326
                "metavar": "<yn>",
327
                "help": "Permission to anonymously submit files and errors",
328
            },
329
        ),
330
        (
331
            "pyta-server-address",
332
            {
333
                "default": "http://127.0.0.1:5000",
334
                "type": "string",
335
                "metavar": "<server-url>",
336
                "help": "Server address to submit anonymous data",
337
            },
338
        ),
339
        (
340
            "messages-config-path",
341
            {
342
                "default": os.path.join(
343
                    os.path.dirname(__file__), "config", "messages_config.toml"
344
                ),
345
                "type": "string",
346
                "metavar": "<messages_config>",
347
                "help": "Path to patch config toml file.",
348
            },
349
        ),
350
        (
351
            "allow-pylint-comments",
352
            {
353
                "default": False,
354
                "type": "yn",
355
                "metavar": "<yn>",
356
                "help": "Allows or disallows 'pylint:' comments",
357
            },
358
        ),
359
        (
360
            "use-pyta-error-messages",
361
            {
362
                "default": True,
363
                "type": "yn",
364
                "metavar": "<yn>",
365
                "help": "Overwrite the default pylint error messages with PythonTA's messages",
366
            },
367
        ),
368
        (
369
            "autoformat-options",
370
            {
371
                "default": ["skip-string-normalization"],
372
                "type": "csv",
373
                "metavar": "<autoformatter options>",
374
                "help": "List of command-line arguments for black",
375
            },
376
        ),
377
    )
378

379
    parent_dir_path = os.path.dirname(__file__)
20✔
380
    custom_checkers = [
20✔
381
        ("python_ta.checkers." + os.path.splitext(f)[0])
382
        for f in listdir(parent_dir_path + "/checkers")
383
        if f != "__init__.py" and os.path.splitext(f)[1] == ".py"
384
    ]
385

386
    # Register new options to a checker here to allow references to
387
    # options in `.pylintrc` config file.
388
    # Options stored in linter: `linter._all_options`, `linter._external_opts`
389
    linter = pylint.lint.PyLinter(options=new_checker_options)
20✔
390
    linter.load_default_plugins()  # Load checkers, reporters
20✔
391
    linter.load_plugin_modules(custom_checkers)
20✔
392
    linter.load_plugin_modules(["python_ta.transforms.setendings"])
20✔
393

394
    default_config_path = find_local_config(os.path.dirname(__file__))
20✔
395
    set_config = load_config
20✔
396

397
    if load_default_config:
20✔
398
        load_config(linter, default_config_path)
20✔
399
        # If we do specify to load the default config, we just need to override the options later.
400
        set_config = override_config
20✔
401

402
    if isinstance(config, str) and config != "":
20✔
403
        set_config(linter, config)
20✔
404
    else:
405
        # If available, use config file at directory of the file being linted.
406
        pylintrc_location = None
20✔
407
        if file_linted:
20✔
408
            pylintrc_location = find_local_config(file_linted)
20✔
409

410
        # Load or override the options if there is a config file in the current directory.
411
        if pylintrc_location:
20✔
UNCOV
412
            set_config(linter, pylintrc_location)
×
413

414
        # Override part of the default config, with a dict of config options.
415
        # Note: these configs are overridden by config file in user's codebase
416
        # location.
417
        if isinstance(config, dict):
20✔
418
            for key in config:
20✔
419
                linter.set_option(key, config[key])
20✔
420

421
    return linter
20✔
422

423

424
def get_file_paths(rel_path: AnyStr) -> Generator[AnyStr, None, None]:
20✔
425
    """A generator for iterating python files within a directory.
426
    `rel_path` is a relative path to a file or directory.
427
    Returns paths to all files in a directory.
428
    """
429
    if not os.path.isdir(rel_path):
20✔
430
        yield rel_path  # Don't do anything; return the file name.
20✔
431
    else:
432
        for root, _, files in os.walk(rel_path):
20✔
433
            for filename in (f for f in files if f.endswith(".py")):
20✔
434
                yield os.path.join(root, filename)  # Format path, from root.
20✔
435

436

437
def _verify_pre_check(filepath: AnyStr, allow_pylint_comments: bool) -> bool:
20✔
438
    """Check student code for certain issues.
439
    The additional allow_pylint_comments parameter indicates whether we want the user to be able to add comments
440
    beginning with pylint which can be used to locally disable checks.
441
    """
442
    # Make sure the program doesn't crash for students.
443
    # Could use some improvement for better logging and error reporting.
444
    try:
20✔
445
        # Check for inline "pylint:" comment, which may indicate a student
446
        # trying to disable a check.
447
        if allow_pylint_comments:
20✔
448
            return True
20✔
449
        with tokenize.open(os.path.expanduser(filepath)) as f:
20✔
450
            for tok_type, content, _, _, _ in tokenize.generate_tokens(f.readline):
20✔
451
                if tok_type != tokenize.COMMENT:
20✔
452
                    continue
20✔
453
                match = OPTION_PO.search(content)
20✔
454
                if match is not None:
20✔
455
                    logging.error(
20✔
456
                        'String "pylint:" found in comment. '
457
                        + "No check run on file `{}.`\n".format(filepath)
458
                    )
459
                    return False
20✔
460
    except IndentationError as e:
20✔
461
        logging.error(
20✔
462
            "python_ta could not check your code due to an "
463
            + "indentation error at line {}.".format(e.lineno)
464
        )
465
        return False
20✔
466
    except tokenize.TokenError as e:
20✔
467
        logging.error(
20✔
468
            "python_ta could not check your code due to a " + "syntax error in your file."
469
        )
470
        return False
20✔
471
    except UnicodeDecodeError:
20✔
472
        logging.error(
20✔
473
            "python_ta could not check your code due to an "
474
            + "invalid character. Please check the following lines "
475
            "in your file and all characters that are marked with a �."
476
        )
477
        with open(os.path.expanduser(filepath), encoding="utf-8", errors="replace") as f:
20✔
478
            for i, line in enumerate(f):
20✔
479
                if "�" in line:
20✔
480
                    logging.error(f"  Line {i + 1}: {line}")
20✔
481
        return False
20✔
482
    return True
20✔
483

484

485
def _get_valid_files_to_check(module_name: Union[list[str], str]) -> Generator[AnyStr, None, None]:
20✔
486
    """A generator for all valid files to check."""
487
    # Allow call to check with empty args
488
    if module_name == "":
20✔
489
        m = sys.modules["__main__"]
10✔
490
        spec = importlib.util.spec_from_file_location(m.__name__, m.__file__)
10✔
491
        module_name = [spec.origin]
10✔
492
    # Enforce API to expect 1 file or directory if type is list
493
    elif isinstance(module_name, str):
20✔
494
        module_name = [module_name]
20✔
495
    # Otherwise, enforce API to expect `module_name` type as list
496
    elif not isinstance(module_name, list):
20✔
497
        logging.error(
20✔
498
            "No checks run. Input to check, `{}`, has invalid type, must be a list of strings.".format(
499
                module_name
500
            )
501
        )
502
        return
20✔
503

504
    # Filter valid files to check
505
    for item in module_name:
20✔
506
        if not isinstance(item, str):  # Issue errors for invalid types
20✔
507
            logging.error(
20✔
508
                "No check run on file `{}`, with invalid type. Must be type: str.\n".format(item)
509
            )
510
        elif os.path.isdir(item):
20✔
511
            yield item
20✔
512
        elif not os.path.exists(os.path.expanduser(item)):
20✔
513
            try:
20✔
514
                # For files with dot notation, e.g., `examples.<filename>`
515
                filepath = modutils.file_from_modpath(item.split("."))
20✔
516
                if os.path.exists(filepath):
×
UNCOV
517
                    yield filepath
×
518
                else:
UNCOV
519
                    logging.error("Could not find the file called, `{}`\n".format(item))
×
520
            except ImportError:
20✔
521
                logging.error("Could not find the file called, `{}`\n".format(item))
20✔
522
        else:
523
            yield item  # Check other valid files.
20✔
524

525

526
def doc(msg_id: str) -> None:
20✔
527
    """Open the PythonTA documentation page for the given error message id.
528

529
    Args:
530
        msg_id: The five-character error code, e.g. ``"E0401"``.
531
    """
532
    msg_url = HELP_URL + "#" + msg_id.lower()
20✔
533
    print("Opening {} in a browser.".format(msg_url))
20✔
534
    webbrowser.open(msg_url)
20✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc