Skip to content

Commit e3fae1d

Browse files
authored
Deepsource fixes (#19)
* Ignore all virtual envs * Fixed PYL-W0102 * State test_patterns * Fix BAN-B101 * Fixed FLK-E501 regression * Skip PYL-E1111 * Skip PYL-W0703 * Fix PYL-W0404 * Fix PYL-W0621 * Clean up unused imports * Fix FLK-E266 * Better variable names * Better global variable naming * Fixed docstring utilities * Fixed FLK-E501 * Cleaned up some trailing whitespace * Fixed PYL-R1705 * Fixed FLK-W291 * Started adding missing docstrings * Removed blank line whitespace * Fix FLK-D200 * Fixed OrderedDict import * Started fixing PYL-W0212 * Created FieldSchema for single-field data validation * Silence PYL-W0212 (no alternative found) * Added a note on our _get_current_object use * Fixed some more PYL-W0212 * Fixed FLK-W293 * Fixed PYL-W0611 * Added dependency_file_paths
1 parent ab52c57 commit e3fae1d

22 files changed

+294
-112
lines changed

.deepsource.toml

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,19 @@
11
version = 1
22

3+
# Glob pattern of the test files
4+
test_patterns = [
5+
"tests/**",
6+
"test_*.py"
7+
]
8+
39
[[analyzers]]
410
name = "python"
511
enabled = true
612

13+
dependency_file_paths = [
14+
"poetry.lock",
15+
"pyproject.toml"
16+
]
17+
718
[analyzers.meta]
819
runtime_version = "3.x.x"

.gitignore

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,8 +102,8 @@ celerybeat.pid
102102
*.sage.py
103103

104104
# Environments
105-
.env
106-
.venv
105+
.env*
106+
.venv*
107107
env/
108108
venv/
109109
ENV/

examples/nested_thing.py

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,9 @@
1717

1818

1919
class DataSet:
20-
def __init__(self, xs, ys):
21-
self.xs = xs
22-
self.ys = ys
20+
def __init__(self, x_values, y_values):
21+
self.xs = x_values
22+
self.ys = y_values
2323

2424

2525
class DataSetSchema(Schema):
@@ -29,19 +29,19 @@ class DataSetSchema(Schema):
2929

3030
class MyComponent:
3131
def __init__(self):
32-
self.id = uuid.uuid4()
32+
self.id = uuid.uuid4() # skipcq: PYL-C0103
3333
self.x_range = range(-100, 100)
3434
self.magic_denoise = 200
3535

36-
def noisy_pdf(self, x, mu=0.0, sigma=25.0):
36+
def noisy_pdf(self, x_value, mu=0.0, sigma=25.0):
3737
"""
3838
Generate a noisy gaussian function (to act as some pretend data)
3939
4040
Our noise is inversely proportional to self.magic_denoise
4141
"""
42-
x = float(x - mu) / sigma
42+
x_value = float(x_value - mu) / sigma
4343
return (
44-
math.exp(-x * x / 2.0) / math.sqrt(2.0 * math.pi) / sigma
44+
math.exp(-x_value * x_value / 2.0) / math.sqrt(2.0 * math.pi) / sigma
4545
+ (1 / self.magic_denoise) * random.random()
4646
)
4747

@@ -60,12 +60,15 @@ class MyComponentSchema(Schema):
6060

6161

6262
"""
63-
Create a view to view and change our magic_denoise value, and register is as a Thing property
63+
Create a view to view and change our magic_denoise value,
64+
and register is as a Thing property
6465
"""
6566

6667

67-
@ThingProperty # Register this view as a Thing Property
68-
@PropertySchema( # Define the data we're going to output (get), and what to expect in (post)
68+
# Register this view as a Thing Property
69+
@ThingProperty
70+
# Define the data we're going to output (get), and what to expect in (post)
71+
@PropertySchema(
6972
fields.Integer(
7073
required=True,
7174
example=200,

examples/properties_dictionary.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,8 @@ def get_state_schema(self):
4646

4747

4848
"""
49-
Create a view to view and change our magic_denoise value, and register is as a Thing property
49+
Create a view to view and change our magic_denoise value,
50+
and register is as a Thing property
5051
"""
5152

5253

@@ -59,18 +60,18 @@ def get(self):
5960
"""Show the current magic_denoise value"""
6061

6162
# When a GET request is made, we'll find our attached component
62-
my_component = find_component("org.labthings.example.mycomponent")
63-
return my_component.get_state()
63+
found_my_component = find_component("org.labthings.example.mycomponent")
64+
return found_my_component.get_state()
6465

6566
# Main function to handle PUT requests (update)
6667
def put(self, new_property_value):
6768
"""Change the current magic_denoise value"""
6869

6970
# Find our attached component
70-
my_component = find_component("org.labthings.example.mycomponent")
71+
found_my_component = find_component("org.labthings.example.mycomponent")
7172

7273
# Apply the new value
73-
return my_component.set_state(new_property_value)
74+
return found_my_component.set_state(new_property_value)
7475

7576

7677
# Create LabThings Flask app

examples/simple_thing.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,7 @@
88
ThingProperty,
99
PropertySchema,
1010
use_args,
11-
use_body,
1211
marshal_task,
13-
marshal_with,
1412
)
1513
from labthings.server.view import View
1614
from labthings.server.find import find_component
@@ -64,12 +62,15 @@ def average_data(self, n: int):
6462

6563

6664
"""
67-
Create a view to view and change our magic_denoise value, and register is as a Thing property
65+
Create a view to view and change our magic_denoise value,
66+
and register is as a Thing property
6867
"""
6968

7069

71-
@ThingProperty # Register this view as a Thing Property
72-
@PropertySchema( # Define the data we're going to output (get), and what to expect in (post)
70+
# Register this view as a Thing Property
71+
@ThingProperty
72+
# Define the data we're going to output (get), and what to expect in (post)
73+
@PropertySchema(
7374
fields.Integer(
7475
required=True,
7576
example=200,
@@ -125,7 +126,8 @@ def get(self):
125126

126127
@ThingAction
127128
class MeasurementAction(View):
128-
# Expect JSON parameters in the request body. Pass to post function as dictionary argument.
129+
# Expect JSON parameters in the request body.
130+
# Pass to post function as dictionary argument.
129131
@use_args(
130132
{
131133
"averages": fields.Integer(

labthings/core/lock.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,15 @@
55

66
class StrictLock(object):
77
"""
8-
Class that behaves like a Python RLock, but with stricter timeout conditions and custom exceptions.
8+
Class that behaves like a Python RLock,
9+
but with stricter timeout conditions and custom exceptions.
910
1011
Args:
11-
timeout (int): Time, in seconds, lock acquisition will wait before raising an exception
12+
timeout (int): Time in seconds acquisition will wait before raising an exception
1213
1314
Attributes:
1415
_lock (:py:class:`threading.RLock`): Parent RLock object
15-
timeout (int): Time, in seconds, lock acquisition will wait before raising an exception
16+
timeout (int): Time in seconds acquisition will wait before raising an exception
1617
"""
1718

1819
def __init__(self, timeout=1):
@@ -46,11 +47,11 @@ class CompositeLock(object):
4647
4748
Args:
4849
locks (list): List of parent RLock objects
49-
timeout (int): Time, in seconds, lock acquisition will wait before raising an exception
50+
timeout (int): Time in seconds acquisition will wait before raising an exception
5051
5152
Attributes:
5253
locks (list): List of parent RLock objects
53-
timeout (int): Time, in seconds, lock acquisition will wait before raising an exception
54+
timeout (int): Time in seconds acquisition will wait before raising an exception
5455
"""
5556

5657
def __init__(self, locks, timeout=1):

labthings/core/tasks/pool.py

Lines changed: 39 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,8 @@ def tasks():
6363
Returns:
6464
list: List of tasks in default taskmaster
6565
"""
66-
global _default_task_master
67-
return _default_task_master.tasks
66+
global DEFAULT_TASK_MASTER
67+
return DEFAULT_TASK_MASTER.tasks
6868

6969

7070
def dict():
@@ -73,8 +73,8 @@ def dict():
7373
Returns:
7474
dict: Dictionary of tasks in default taskmaster
7575
"""
76-
global _default_task_master
77-
return _default_task_master.dict
76+
global DEFAULT_TASK_MASTER
77+
return DEFAULT_TASK_MASTER.dict
7878

7979

8080
def states():
@@ -83,38 +83,65 @@ def states():
8383
Returns:
8484
dict: Dictionary of task states in default taskmaster
8585
"""
86-
global _default_task_master
87-
return _default_task_master.states
86+
global DEFAULT_TASK_MASTER
87+
return DEFAULT_TASK_MASTER.states
8888

8989

9090
def cleanup_tasks():
91-
global _default_task_master
92-
return _default_task_master.cleanup()
91+
"""Remove all finished tasks from the task list"""
92+
global DEFAULT_TASK_MASTER
93+
return DEFAULT_TASK_MASTER.cleanup()
9394

9495

9596
def remove_task(task_id: str):
96-
global _default_task_master
97-
return _default_task_master.remove(task_id)
97+
"""Remove a particular task from the task list
98+
99+
Arguments:
100+
task_id {str} -- ID of the target task
101+
"""
102+
global DEFAULT_TASK_MASTER
103+
return DEFAULT_TASK_MASTER.remove(task_id)
98104

99105

100106
# Operations on the current task
101107

102108

103109
def current_task():
110+
"""Return the Task instance in which the caller is currently running.
111+
112+
If this function is called from outside a Task thread, it will return None.
113+
114+
Returns:
115+
TaskThread -- Currently running Task thread.
116+
"""
104117
current_task_thread = threading.current_thread()
105118
if not isinstance(current_task_thread, TaskThread):
106119
return None
107120
return current_task_thread
108121

109122

110123
def update_task_progress(progress: int):
124+
"""Update the progress of the Task in which the caller is currently running.
125+
126+
If this function is called from outside a Task thread, it will do nothing.
127+
128+
Arguments:
129+
progress {int} -- Current progress, in percent (0-100)
130+
"""
111131
if current_task():
112132
current_task().update_progress(progress)
113133
else:
114134
logging.info("Cannot update task progress of __main__ thread. Skipping.")
115135

116136

117137
def update_task_data(data: dict):
138+
"""Update the data of the Task in which the caller is currently running.
139+
140+
If this function is called from outside a Task thread, it will do nothing.
141+
142+
Arguments:
143+
data {dict} -- Additional data to merge with the Task data
144+
"""
118145
if current_task():
119146
current_task().update_data(data)
120147
else:
@@ -132,7 +159,7 @@ def taskify(f):
132159

133160
@wraps(f)
134161
def wrapped(*args, **kwargs):
135-
task = _default_task_master.new(
162+
task = DEFAULT_TASK_MASTER.new(
136163
f, *args, **kwargs
137164
) # Append to parent object's task list
138165
task.start() # Start the function
@@ -142,4 +169,4 @@ def wrapped(*args, **kwargs):
142169

143170

144171
# Create our default, protected, module-level task pool
145-
_default_task_master = TaskMaster()
172+
DEFAULT_TASK_MASTER = TaskMaster()

labthings/core/tasks/thread.py

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ class ThreadTerminationError(SystemExit):
1414

1515

1616
class TaskThread(threading.Thread):
17-
def __init__(self, target=None, name=None, args=(), kwargs={}, daemon=True):
17+
def __init__(self, target=None, name=None, args=None, kwargs=None, daemon=True):
1818
threading.Thread.__init__(
1919
self,
2020
group=None,
@@ -24,6 +24,11 @@ def __init__(self, target=None, name=None, args=(), kwargs={}, daemon=True):
2424
kwargs=kwargs,
2525
daemon=daemon,
2626
)
27+
# Handle arguments
28+
if args is None:
29+
args = ()
30+
if kwargs is None:
31+
kwargs = {}
2732

2833
# A UUID for the TaskThread (not the same as the threading.Thread ident)
2934
self._ID = uuid.uuid4() # Task ID
@@ -96,7 +101,7 @@ def wrapped(*args, **kwargs):
96101
try:
97102
self._return_value = f(*args, **kwargs)
98103
self._status = "success"
99-
except Exception as e:
104+
except Exception as e: # skipcq: PYL-W0703
100105
logging.error(e)
101106
logging.error(traceback.format_exc())
102107
self._return_value = str(e)
@@ -133,7 +138,11 @@ def wait(self):
133138
def async_raise(self, exc_type):
134139
"""Raise an exception in this thread."""
135140
# Should only be called on a started thread, so raise otherwise.
136-
assert self.ident is not None, "Only started threads have thread identifier"
141+
if self.ident is None:
142+
raise RuntimeError(
143+
"Cannot halt a thread that hasn't started. "
144+
"No valid running thread identifier."
145+
)
137146

138147
# If the thread has died we don't want to raise an exception so log.
139148
if not self.is_alive():
@@ -166,7 +175,7 @@ def _is_thread_proc_running(self):
166175
Returns:
167176
bool: If _thread_proc is currently running
168177
"""
169-
could_acquire = self._running_lock.acquire(0)
178+
could_acquire = self._running_lock.acquire(False) # skipcq: PYL-E1111
170179
if could_acquire:
171180
self._running_lock.release()
172181
return False

0 commit comments

Comments
 (0)