Skip to content

Commit 369663c

Browse files
committed
Exempt examples from fewer ruff linting rules
1 parent 4101717 commit 369663c

13 files changed

Lines changed: 48 additions & 40 deletions

examples/annotated_example.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@ def do_add(self, a: int, b: int = 0, verbose: bool = False) -> None:
9999
Examples:
100100
add 2 --b 3
101101
add 10 --b 5 --verbose
102+
102103
"""
103104
result = a + b
104105
if verbose:

examples/argparse_example.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -125,13 +125,13 @@ def do_print_unknown(self, args: argparse.Namespace, unknown: list[str]) -> None
125125
# subcommand functions for the calculate command
126126
@cmd2.as_subcommand_to("calculate", "add", add_parser, help=add_description.lower())
127127
def add(self, args: argparse.Namespace) -> None:
128-
"""add subcommand of calculate command."""
128+
"""Add subcommand of calculate command."""
129129
result = args.num1 + args.num2
130130
self.poutput(f"{args.num1} + {args.num2} = {result}")
131131

132132
@cmd2.as_subcommand_to("calculate", "subtract", subtract_parser, help=subtract_description.lower())
133133
def subtract(self, args: argparse.Namespace) -> None:
134-
"""subtract subcommand of calculate command."""
134+
"""Subtract subcommand of calculate command."""
135135
result = args.num1 - args.num2
136136
self.poutput(f"{args.num1} - {args.num2} = {result}")
137137

examples/async_call.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313

1414
def run_async(coro) -> concurrent.futures.Future:
1515
"""Await a coroutine from a synchronous function/method."""
16-
1716
global _event_loop # noqa: PLW0603
1817

1918
if _event_loop is None:
@@ -31,7 +30,7 @@ def run_async(coro) -> concurrent.futures.Future:
3130

3231

3332
async def async_wait(duration: float) -> float:
34-
"""Example async function that is called from a synchronous cmd2 command"""
33+
"""Example async function that is called from a synchronous cmd2 command."""
3534
await asyncio.sleep(duration)
3635
return duration
3736

@@ -47,7 +46,6 @@ def do_async_wait(self, _: str) -> None:
4746
4847
Example cmd2 command that calls an async function.
4948
"""
50-
5149
waitable = run_async(async_wait(0.1))
5250
self.poutput("Begin waiting...")
5351
# Wait for coroutine to complete and get its return value:

examples/async_commands.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
import asyncio
99
import functools
10-
import random
10+
import secrets
1111
import shutil
1212
import threading
1313
from collections.abc import Callable
@@ -46,7 +46,6 @@ def _get_event_loop() -> asyncio.AbstractEventLoop:
4646
def with_async_loop(func: Callable[..., Any], cancel_on_interrupt: bool = True) -> Callable[..., Any]:
4747
"""Decorate an async ``do_*`` command method to give it access to the event loop.
4848
49-
5049
This decorator wraps a do_* command method. When the command is executed,
5150
it submits the coroutine returned by the method to a background asyncio loop
5251
and waits for the result synchronously (blocking the cmd2 loop, as expected
@@ -79,6 +78,9 @@ def __init__(self) -> None:
7978
super().__init__()
8079
self.intro = 'Welcome to the Async Commands example. Type "help" to see available commands.'
8180

81+
# Create an instance of SystemRandom
82+
self._secure_generator = secrets.SystemRandom()
83+
8284
if self.main_session.key_bindings is None:
8385
self.main_session.key_bindings = KeyBindings()
8486

@@ -118,14 +120,14 @@ def handle_control_t(self, _event) -> None:
118120
word = "fnord"
119121

120122
# Generate a random RGB color tuple
121-
r = random.randint(0, 255)
122-
g = random.randint(0, 255)
123-
b = random.randint(0, 255)
123+
r = self._secure_generator.randint(0, 255)
124+
g = self._secure_generator.randint(0, 255)
125+
b = self._secure_generator.randint(0, 255)
124126

125127
# Get terminal width to calculate padding for right-alignment
126128
cols, _ = shutil.get_terminal_size()
127129
extra_width = cols - len(word) - 1
128-
padding_size = random.randint(0, extra_width)
130+
padding_size = self._secure_generator.randint(0, extra_width)
129131
padding = " " * padding_size
130132

131133
# Use rich to generate the overall text to print out

examples/async_printing.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
and changes the window title.
44
"""
55

6-
import random
6+
import secrets
77
import threading
88
import time
99

@@ -46,6 +46,9 @@ def __init__(self) -> None:
4646
self.register_preloop_hook(self._preloop_hook)
4747
self.register_postloop_hook(self._postloop_hook)
4848

49+
# Create an instance of SystemRandom
50+
self._secure_generator = secrets.SystemRandom()
51+
4952
def _preloop_hook(self) -> None:
5053
"""Start the alerter thread."""
5154
self._stop_event.clear()
@@ -91,7 +94,7 @@ def _get_alerts(self) -> list[str]:
9194
self._next_alert_time = cur_time + 4
9295

9396
else:
94-
rand_num = random.randint(1, 20)
97+
rand_num = self._secure_generator.randint(1, 20)
9598
if rand_num > 2:
9699
return []
97100

@@ -129,7 +132,7 @@ def _build_colored_prompt(self) -> str:
129132
"""Randomly builds a colored prompt
130133
:return: the new prompt.
131134
"""
132-
rand_num = random.randint(1, 6)
135+
rand_num = self._secure_generator.randint(1, 6)
133136

134137
status_color = Color.DEFAULT
135138

examples/cmd_as_argument.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
"""
99

1010
import argparse
11-
import random
11+
import secrets
1212

1313
import cmd2
1414

@@ -31,6 +31,9 @@ def __init__(self) -> None:
3131
# Make maxrepeats settable at runtime
3232
self.add_settable(cmd2.Settable("maxrepeats", int, "max repetitions for speak command", self))
3333

34+
# Create an instance of SystemRandom
35+
self._secure_generator = secrets.SystemRandom()
36+
3437
speak_parser = cmd2.Cmd2ArgumentParser()
3538
speak_parser.add_argument("-p", "--piglatin", action="store_true", help="atinLay")
3639
speak_parser.add_argument("-s", "--shout", action="store_true", help="N00B EMULATION MODE")
@@ -41,7 +44,8 @@ def __init__(self) -> None:
4144
def do_speak(self, args) -> None:
4245
"""Repeats what you tell me to."""
4346
words = []
44-
for word in args.words:
47+
for w in args.words:
48+
word = w.copy()
4549
if args.piglatin:
4650
word = f"{word[1:]}{word[0]}ay"
4751
if args.shout:
@@ -65,14 +69,14 @@ def do_mumble(self, args) -> None:
6569
repetitions = args.repeat or 1
6670
for _ in range(min(repetitions, self.maxrepeats)):
6771
output = []
68-
if random.random() < 0.33:
69-
output.append(random.choice(self.MUMBLE_FIRST))
72+
if self._secure_generator.random() < 0.33:
73+
output.append(secrets.choice(self.MUMBLE_FIRST))
7074
for word in args.words:
71-
if random.random() < 0.40:
72-
output.append(random.choice(self.MUMBLES))
75+
if self._secure_generator.random() < 0.40:
76+
output.append(secrets.choice(self.MUMBLES))
7377
output.append(word)
74-
if random.random() < 0.25:
75-
output.append(random.choice(self.MUMBLE_LAST))
78+
if self._secure_generator.random() < 0.25:
79+
output.append(secrets.choice(self.MUMBLE_LAST))
7680
self.poutput(" ".join(output))
7781

7882

examples/completion_item_choices.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
#!/usr/bin/env python
2-
"""
3-
Demonstrates using CompletionItem instances as elements in an argparse choices list.
2+
"""Demonstrates using CompletionItem instances as elements in an argparse choices list.
43
54
Technical Note:
65
Using 'choices' is best for fixed datasets that do not change during the
@@ -53,7 +52,7 @@
5352
class Account:
5453
"""A complex object that we want to select by a friendly name."""
5554

56-
def __init__(self, account_id: int, owner: str):
55+
def __init__(self, account_id: int, owner: str) -> None:
5756
self.account_id = account_id
5857
self.owner = owner
5958

examples/custom_parser.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
"""
2-
The standard parser used by cmd2 built-in commands is Cmd2ArgumentParser.
1+
"""The standard parser used by cmd2 built-in commands is Cmd2ArgumentParser.
32
The following code shows how to override it with your own parser class.
43
"""
54

examples/migrating.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
# import cmd2 as cmd # noqa: ERA001
55
import cmd # Comment this line and uncomment the one above to migrate to cmd2
6-
import random
6+
import secrets
77

88

99
class CmdLineApp(cmd.Cmd):
@@ -13,6 +13,10 @@ class CmdLineApp(cmd.Cmd):
1313
MUMBLE_FIRST = ("so", "like", "well")
1414
MUMBLE_LAST = ("right?",)
1515

16+
def __init__(self) -> None:
17+
super().__init__()
18+
self._secure_generator = secrets.SystemRandom()
19+
1620
def do_exit(self, _line) -> bool:
1721
"""Exit the application."""
1822
return True
@@ -30,14 +34,14 @@ def do_mumble(self, line) -> None:
3034
"""Mumbles what you tell me to."""
3135
words = line.split(" ")
3236
output = []
33-
if random.random() < 0.33:
34-
output.append(random.choice(self.MUMBLE_FIRST))
37+
if self._secure_generator.random() < 0.33:
38+
output.append(secrets.choice(self.MUMBLE_FIRST))
3539
for word in words:
36-
if random.random() < 0.40:
37-
output.append(random.choice(self.MUMBLES))
40+
if self._secure_generator.random() < 0.40:
41+
output.append(secrets.choice(self.MUMBLES))
3842
output.append(word)
39-
if random.random() < 0.25:
40-
output.append(random.choice(self.MUMBLE_LAST))
43+
if self._secure_generator.random() < 0.25:
44+
output.append(secrets.choice(self.MUMBLE_LAST))
4145
print(" ".join(output), file=self.stdout)
4246

4347

examples/read_input.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ def do_read_password(self, _) -> None:
111111
except EOFError:
112112
pass
113113

114-
def do_eat(self, arg):
114+
def do_eat(self, arg) -> None:
115115
"""Example of using the select method for reading multiple choice input.
116116
117117
Usage: eat wheatties

0 commit comments

Comments
 (0)