









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!










This practice lab exam assesses mastery of Python static code analysis using Flake
(pycodestyle, pyflakes, mccabe), PEP 8 style enforcement, secure coding principles,
defect detection, and integration of linting into development workflows. Questions
require multi-step reasoning, interpretation of tool output, configuration synthesis, and
remediation of security-relevant code smells.
A. flake8 --max-line-length=100 --extend-ignore=E203,W B. flake8 --max-line-length=100 --ignore=E203,W C. flake8 --line-length=100 --select=E203,W D. flake8 --max-line-length=100 --exclude=E203,W
--extend-ignore adds codes to the default ignore list, preserving other defaults; --ignore replaces the entire default ignore set, which can unexpectedly enable other checks. --line-length is not a valid Flake8 option, and --exclude is for file patterns, not error codes. Thus A is correct.
A. Dead code may hide injected malicious logic or stale credentials. B. The variable could be used before assignment, causing a runtime error. C. It indicates a missing import that will raise NameError at runtime. D. It signals a race condition in multithreaded execution.
Unused assignments often mask dead code that attackers may exploit to conceal backdoors or leftover secrets; removing them reduces attack surface. The other options describe different defect classes (use-before-assignment, missing imports, concurrency) not signaled by this message.
Flake8 exits with status 1 when lint violations are detected, which CI systems interpret as failure. Exit 0 means clean, while 2 and 3 are not standard Flake violation exit codes.
A. Remove the unused import to reduce namespace pollution and attack surface. B. Add '# noqa' to silence the warning without changing code. C. Replace with 'import os' and use os.path later. D. Move the import inside a function to defer execution.
Removing unused imports eliminates dead code and reduces namespace pollution, aligning with least-privilege and attack-surface reduction. Suppressing with # noqa hides the issue, and deferring imports does not address the unused symbol.
A. Two blank lines before top-level function definitions. B. One blank line before top-level function definitions. C. No blank lines before top-level function definitions. D. Two blank lines after top-level function definitions.
E302 requires two blank lines before top-level function and class definitions per PEP 8. E301 covers one blank line for methods, and the other options misstate the rule.
A. files: \.py$ with pass_filenames: true B. types: [python] with pass_filenames: false C. exclude: \.py$ with pass_filenames: true D. language: python with files: .*
pre-commit passes staged filenames when pass_filenames is true, and the regex files: \.py$ restricts to Python files. Setting pass_filenames false would run Flake8 on the whole repo, and exclude would do the opposite.
A. Extract cohesive branches into helper functions with clear names. B. Add '# noqa: C901' to suppress the warning. C. Replace nested ifs with a single long boolean expression. D. Move the function to a separate module without changes.
Extracting cohesive branches into helper functions reduces cyclomatic complexity and improves auditability, a core secure-coding practice. Suppression hides risk, a long boolean expression may not reduce complexity, and moving the function does not change its complexity.
A. The plugin's entry point in setup.py must declare a flake8.extension group and return (line, col, message, type) tuples. B. The plugin must subclass flake8.plugins.finder.Checker and override the report() method. C. The plugin must register a callback via flake8.api.hooks and raise a Flake8Error exception. D. The plugin must define a class with a run() method that yields flake8.style_guide.Violation objects.
Flake8 discovers custom checkers through the flake8.extension entry point group, and checkers yield (line, col, message, type) tuples where the message begins with the error code (e.g., 'X100'). The other options misstate the plugin API: there is no Checker subclass with report(), no flake8.api.hooks callback mechanism for checkers, and Violation objects are internal to style_guide, not yielded by plugins.
A. Because flake8's default rule set and plugin behavior can change between releases, altering findings. B. Because unpinned flake8 versions cannot parse Python 3.12 syntax. C. Because pre-commit requires a git tag, not a version number, for Python tools. D. Because flake8 only runs under pre-commit when installed as a system package.
Flake8 and its bundled pycodestyle/pyflakes evolve; new releases add, change, or remove checks and defaults, so pinning ensures consistent results across developer machines and CI. Unpinned versions do parse modern syntax, pre-commit accepts version numbers (rev), and flake8 runs in an isolated environment, not a system package.
A. Disable flake8 locally and rely solely on post-merge CI scans. B. Configure pre-commit hooks with the same flake8 config plus a CI gate on the default branch. C. Replace flake8 with a runtime dynamic analysis tool for all checks. D. Allow --exit-zero locally and enforce failures only in production monitoring.
Aligning local pre-commit hooks with the CI configuration gives fast feedback and prevents bypass while a CI gate on the default branch provides a hard backstop. Relying only on post-merge scans (A) delays remediation, dynamic analysis (C) cannot replace static checks, and --exit-zero (D) suppresses failures entirely.
A. Suppresses all Flake8 warnings on that line. B. Suppresses only the F401 warning on that line. C. Suppresses F401 for the entire file. D. Causes Flake8 to ignore the file entirely.
A targeted '# noqa: F401' suppresses only the specified code on that physical line, preserving other checks. Bare '# noqa' would suppress all warnings on the line (A), while file-wide or file-level suppression requires different mechanisms (e.g., per-file-ignores or '# flake8: noqa').
A. Set select = E,W,F and ignore = (empty) to enforce all rules. B. Use per-file-ignores to suppress specific codes in legacy modules while enforcing them in new code. C. Disable flake8 entirely and rely on manual code review. D. Set max-line-length = 200 and ignore = E501 only.
Per-file-ignores allows targeted suppression in legacy files without weakening standards for new code, balancing remediation and enforcement. Enforcing all rules (A) floods the report with legacy noise, disabling flake8 (C) removes static analysis, and ignoring only E501 (D) leaves many false positives unaddressed.
A. 79, because the per-file config overrides setup.cfg. B. 100, because setup.cfg has higher precedence than .flake8. C. Flake8 errors out due to conflicting configuration. D. 79 and 100 are both enforced, reporting E501 at the stricter limit.
Flake8's configuration precedence is: command-line > setup.cfg/tox.ini/.flake8 in the current directory > per-user config > global. A local setup.cfg takes precedence over a .flake8 file, so max-line-length=100 wins. The ignore list is merged, but the numeric limit is taken from the highest-precedence source.
A. flake8 --select=E,W --max-complexity= B. flake8 --select=F --extend-select=B --max-complexity= C. flake8 --ignore=E501,W D. flake8 --select=C
Selecting F (pyflakes) plus B (bugbear security/robustness checks) and enforcing cyclomatic complexity targets logic and security issues while excluding pure style (E/W). Option A enforces style; C ignores style but does not add security plugins; D only checks complexity.
A. C901; high complexity increases untested branches and latent vulnerabilities. B. E501; long lines obscure security review. C. F401; unused imports indicate dead code. D. W605; invalid escape sequences enable injection.
McCabe's C901 is emitted when complexity exceeds the threshold; high complexity correlates with more execution paths, making comprehensive testing harder and hiding security defects. E501 is line length, F401 is unused imports, and W605 is invalid escape sequences-none relate to complexity.
A. pycodestyle E225 missing whitespace around operator B. flake8-bandit S105 hardcoded password string C. mccabe C901 function too complex D. pyflakes F841 local variable assigned but never used
flake8-bandit wraps Bandit checks; S105 specifically flags hardcoded password strings, aligning with CWE-798. E225 is style, C901 is complexity, and F841 is an unused variable-none directly detect embedded credentials.
A. [flake8]\nignore = E501\nmax-complexity = 10 B. [flake8]\ndisable = E501\ncomplexity = 10 C. [pycodestyle]\nignore = E501\nmax_complexity = 10 D. [flake8]\nskip = E501\nmccabe = 10
Flake8 reads the [flake8] section, using 'ignore' for codes and 'max-complexity' for the mccabe threshold. 'disable', 'complexity', and 'skip/mccabe' are not valid Flake8 option names, and [pycodestyle] would not configure Flake8's mccabe check. Correct option syntax is essential for reproducible linting.
A. No C901 is reported because max-complexity defaults to -1 (disabled) B. C901 is reported because the default threshold is 10 C. C901 is reported only if --max-complexity is set to 12 D. W901 is reported by pycodestyle for excessive complexity
Flake8's mccabe check is disabled by default (max-complexity = -1), so C901 is not emitted unless configured. Option B assumes a default threshold that does not exist, C misstates the trigger, and W901 is not a real code. Understanding default-off behavior prevents false expectations.
A. Run flake8 --diff against the merge base and fail only on new violations B. Run flake8 on the entire repository and fail on any violation C. Run flake8 with --exit-zero to always succeed D. Run flake8 only on files changed in the last commit using git ls-files
Using --diff against the merge base reports only violations introduced by the change, enabling incremental enforcement. Failing on the whole repo blocks legacy code, --exit-zero never fails, and last-commit-only misses broader changes. This is a standard secure-CI pattern.
A. # noqa: F401 suppresses only F401 on that line; bare # noqa suppresses all codes B. # noqa always suppresses all codes regardless of the code list C. # noqa: F401 suppresses F401 for the entire file D. # noqa is ignored unless --enable-noqa is passed
Flake8 supports code-specific suppression via '# noqa: CODE', while a bare '# noqa' suppresses all violations on that line. It is line-scoped, not file-scoped, and requires no extra flag. Precise suppression avoids masking unrelated issues.
A. max-complexity must be set below 12 in the flake8 configuration. B. C901 is enabled by default and triggers at complexity 10 or higher. C. mccabe checks require the --max-line-length flag to be set explicitly. D. C901 is a pyflakes code and fires on any function with nested loops.
Flake8's mccabe plugin emits C901 only when --max-complexity is configured and the function's complexity exceeds that threshold; setting it below 12 triggers the warning. C901 is not on by default (B), unrelated to line length (C), and is a mccabe not pyflakes code (D).
A. Run flake8 only in nightly builds and ignore results during releases. B. Use pre-commit with flake8; allow bypass via --no-verify with logged justification. C. Embed flake8 in the IDE only and rely on developer discipline to fix issues. D. Configure flake8 --exit-zero in pre-commit so commits never fail.
A pre-commit hook enforces flake8 locally while permitting an auditable bypass (git commit --no-verify) for emergencies, balancing security and availability. Nightly-only (A) and IDE-only (C) checks are easily skipped, and --exit-zero (D) defeats the gate entirely.
A. F403 star-import obscures namespace, enabling shadowing of security functions. B. E501 line too long, reducing readability of the import statement. C. F841 unused variable, indicating dead code in the module. D. W605 invalid escape sequence, signaling regex injection risk.
Pyflakes flags wildcard imports as F403 because they pollute the namespace and can silently shadow security-critical names, a real supply-chain and correctness risk. E501, F841, and W605 are unrelated style or local-variable findings.
A. pycodestyle detects logical errors; pyflakes enforces PEP 8 formatting. B. pycodestyle enforces PEP 8 style (E/W); pyflakes detects logical errors (F). C. Both plugins perform identical checks; flake8 merges duplicate outputs. D. pyflakes enforces PEP 8; pycodestyle performs complexity analysis (C901).
Flake8 wraps pycodestyle for PEP 8 style codes (E/W) and pyflakes for logical/name errors (F), while mccabe handles C901. Options A and D invert roles, and C falsely claims identical checks.