Skip to content

Commit c4e314e

Browse files
committed
Format modules with ruff
1 parent 807c69e commit c4e314e

File tree

205 files changed

+1394
-4060
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

205 files changed

+1394
-4060
lines changed

modules/photons_app/collector.py

Lines changed: 14 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,13 @@
1010
from delfick_project.errors import DelfickError
1111
from delfick_project.norms import Meta, dictobj, sb
1212
from delfick_project.option_merge import Collector, MergedOptions
13+
from photons_messages import protocol_register
14+
1315
from photons_app import helpers as hp
1416
from photons_app.errors import BadConfiguration, BadYaml, UserQuit
1517
from photons_app.formatter import MergedOptionStringFormatter
1618
from photons_app.photons_app import PhotonsAppSpec
1719
from photons_app.tasks.runner import Runner
18-
from photons_messages import protocol_register
1920

2021
log = logging.getLogger("photons_app.collector")
2122

@@ -73,9 +74,7 @@ def setup(self, source):
7374
self.extras_spec = Extras.FieldSpec()
7475

7576
def normalise_filled(self, meta, val):
76-
options_spec = sb.set_options(
77-
filename=sb.required(sb.string_spec()), optional=sb.defaulted(sb.boolean(), False)
78-
)
77+
options_spec = sb.set_options(filename=sb.required(sb.string_spec()), optional=sb.defaulted(sb.boolean(), False))
7978
lst_spec = sb.listof(sb.or_spec(sb.string_spec(), options_spec))
8079

8180
if isinstance(val, list):
@@ -156,8 +155,8 @@ def run_coro_as_main(self, coro, catch_delfick_error=True):
156155

157156
print("")
158157
print("!" * 80)
159-
print("Something went wrong! -- {0}".format(error.__class__.__name__))
160-
print("\t{0}".format(error))
158+
print(f"Something went wrong! -- {error.__class__.__name__}")
159+
print(f"\t{error}")
161160
if conf["photons_app"].debug:
162161
raise
163162
sys.exit(1)
@@ -210,7 +209,10 @@ def extra_prepare(self, configuration, args_dict):
210209

211210
def find_photons_app_options(self, configuration, args_dict):
212211
"""Return us all the photons_app options"""
213-
d = lambda r: {} if r in (None, "", sb.NotSpecified) else r
212+
213+
def d(r):
214+
return {} if r in (None, "", sb.NotSpecified) else r
215+
214216
return MergedOptions.using(
215217
dict(d(configuration.get("photons_app")).items()),
216218
dict(d(args_dict.get("photons_app")).items()),
@@ -225,13 +227,8 @@ def determine_mainline_module(self):
225227
except ImportError:
226228
pass
227229
else:
228-
if any(
229-
hasattr(getattr(__main__, attr, None), "_delfick_project_addon_entry")
230-
for attr in dir(__main__)
231-
):
232-
sys.meta_path = [
233-
thing for thing in sys.meta_path if not isinstance(thing, MainFinder)
234-
]
230+
if any(hasattr(getattr(__main__, attr, None), "_delfick_project_addon_entry") for attr in dir(__main__)):
231+
sys.meta_path = [thing for thing in sys.meta_path if not isinstance(thing, MainFinder)]
235232
sys.meta_path.append(MainFinder(__main__))
236233
else:
237234
__main__ = None
@@ -276,9 +273,7 @@ def extra_prepare_after_activation(self, configuration, args_dict):
276273
This will determine the target and artifact for you given the
277274
configuration in the collector.
278275
"""
279-
configuration.update(
280-
{"final_future": configuration["photons_app"].final_future}, source="<photons_app>"
281-
)
276+
configuration.update({"final_future": configuration["photons_app"].final_future}, source="<photons_app>")
282277

283278
# Post register our addons
284279
extra_args = {"lifx.photons": {}}
@@ -314,7 +309,7 @@ def read_file(self, location):
314309
"Failed to read yaml",
315310
location=location,
316311
error_type=error.__class__.__name__,
317-
error="{0}{1}".format(error.problem, error.problem_mark),
312+
error=f"{error.problem}{error.problem_mark}",
318313
)
319314

320315
def add_configuration(self, configuration, collect_another_source, done, result, src):
@@ -329,9 +324,7 @@ def add_configuration(self, configuration, collect_another_source, done, result,
329324
if "config_root" in configuration:
330325
# if we already have a config root then we only keep new config root if it's not the home location
331326
# i.e. if it is the home configuration, we don't delete the new config_root
332-
if configuration["config_root"] != os.path.dirname(
333-
self.home_dir_configuration_location()
334-
):
327+
if configuration["config_root"] != os.path.dirname(self.home_dir_configuration_location()):
335328
if "config_root" in result:
336329
del result["config_root"]
337330

modules/photons_app/executor.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,13 @@
1010

1111
from delfick_project.app import App, OptionalFileType
1212
from delfick_project.norms import sb
13+
1314
from photons_app import VERSION
1415
from photons_app.collector import Collector
1516
from photons_app.tasks import task_register
1617

1718

18-
def library_setup(
19-
config_filename="lifx.yml", photons_modules=True, extra_files=None, photons_app_options=None
20-
):
19+
def library_setup(config_filename="lifx.yml", photons_modules=True, extra_files=None, photons_app_options=None):
2120
"""
2221
Get us a setup photons Collector instance.
2322
@@ -108,7 +107,7 @@ def mainline(self, argv=None, print_errors_to=sys.stdout, **execute_args):
108107
if task in ("list_tasks", "help"):
109108
os.environ["PHOTONS_SILENT_BY_DEFAULT"] = "1"
110109

111-
super(App, self).mainline(original_argv, print_errors_to, **execute_args)
110+
super().mainline(original_argv, print_errors_to, **execute_args)
112111

113112
def setup_collector(self, args_dict, logging_handler, extra_files):
114113
"""Create and initialize a collector"""

modules/photons_app/formatter.py

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import operator
2121

2222
from delfick_project.option_merge import MergedOptionStringFormatter
23+
2324
from photons_app import helpers as hp
2425

2526

@@ -68,12 +69,6 @@ def special_format_field(self, obj, format_spec):
6869
"""Know about any special formats"""
6970
if format_spec == "resource":
7071
parts = obj.split("/")
71-
return str(
72-
functools.reduce(
73-
operator.truediv, [importlib.resources.files(parts[0]), *parts[1:]]
74-
).resolve()
75-
)
76-
elif any(
77-
isinstance(obj, f) for f in (asyncio.Future, hp.ChildOfFuture, hp.ResettableFuture)
78-
):
72+
return str(functools.reduce(operator.truediv, [importlib.resources.files(parts[0]), *parts[1:]]).resolve())
73+
elif any(isinstance(obj, f) for f in (asyncio.Future, hp.ChildOfFuture, hp.ResettableFuture)):
7974
return obj

modules/photons_app/helpers.py

Lines changed: 23 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,10 @@
1313
from queue import Queue as NormalQueue
1414

1515
from delfick_project.logging import lc
16-
from photons_app.errors import PhotonsAppError
1716
from photons_messages import fields
1817

18+
from photons_app.errors import PhotonsAppError
19+
1920
log = logging.getLogger("photons_app.helpers")
2021

2122
# Make vim be quiet
@@ -69,7 +70,7 @@ def __eq__(self, other):
6970

7071
other = Color(*other)
7172

72-
if not isinstance(other, (fields.Color, dict)) and not hasattr(other, "as_dict"):
73+
if not isinstance(other, dict | fields.Color) and not hasattr(other, "as_dict"):
7374
return False
7475

7576
if not isinstance(other, fields.Color):
@@ -120,11 +121,7 @@ def __eq__(self, other):
120121
if isinstance(other, tuple) and len(other) == 2:
121122
return (self.major, self.minor) == other
122123
elif isinstance(other, Firmware):
123-
return (
124-
self.major == other.major
125-
and self.minor == other.minor
126-
and self.build == other.build
127-
)
124+
return self.major == other.major and self.minor == other.minor and self.build == other.build
128125
else:
129126
raise ValueError(f"Can't compare firmware with {type(other)}: {other}")
130127

@@ -181,7 +178,7 @@ async def ensure_aexit_cm():
181178
exc_info = None
182179
try:
183180
yield
184-
except:
181+
except Exception:
185182
exc_info = sys.exc_info()
186183

187184
if exc_info is not None:
@@ -355,8 +352,7 @@ def __init__(
355352

356353
self.waiter = ResettableFuture(name=f"ATicker({self.name})::__init__[waiter]")
357354
self.final_future = ChildOfFuture(
358-
final_future
359-
or create_future(name=f"ATicker({self.name})::__init__[owned_final_future]"),
355+
final_future or create_future(name=f"ATicker({self.name})::__init__[owned_final_future]"),
360356
name=f"ATicker({self.name})::__init__[final_future]",
361357
)
362358

@@ -366,17 +362,13 @@ async def start(self):
366362

367363
def __aiter__(self):
368364
if not hasattr(self, "gen"):
369-
raise Exception(
370-
"The ticker must be used as a context manager before being used as an async iterator"
371-
)
365+
raise Exception("The ticker must be used as a context manager before being used as an async iterator")
372366
return self.gen
373367

374368
async def finish(self, exc_typ=None, exc=None, tb=None):
375369
if hasattr(self, "gen"):
376370
try:
377-
await stop_async_generator(
378-
self.gen, exc=exc or self.Stop(), name=f"ATicker({self.name})::stop[stop_gen]"
379-
)
371+
await stop_async_generator(self.gen, exc=exc or self.Stop(), name=f"ATicker({self.name})::stop[stop_gen]")
380372
except self.Stop:
381373
pass
382374

@@ -440,9 +432,7 @@ async def pause():
440432
async with self.pauser:
441433
pass
442434

443-
ts_final_future = ChildOfFuture(
444-
self.final_future, name=f"ATicker({self.name})::_wait_for_next[with_pause]"
445-
)
435+
ts_final_future = ChildOfFuture(self.final_future, name=f"ATicker({self.name})::_wait_for_next[with_pause]")
446436

447437
async with TaskHolder(ts_final_future) as ts:
448438
ts.add(pause())
@@ -605,14 +595,10 @@ def __init__(self, final_future, *, name=None):
605595
self.name = name
606596

607597
self.ts = []
608-
self.final_future = ChildOfFuture(
609-
final_future, name=f"TaskHolder({self.name})::__init__[final_future]"
610-
)
598+
self.final_future = ChildOfFuture(final_future, name=f"TaskHolder({self.name})::__init__[final_future]")
611599

612600
self._cleaner = None
613-
self._cleaner_waiter = ResettableFuture(
614-
name=f"TaskHolder({self.name})::__init__[cleaner_waiter]"
615-
)
601+
self._cleaner_waiter = ResettableFuture(name=f"TaskHolder({self.name})::__init__[cleaner_waiter]")
616602

617603
def add(self, coro, *, silent=False):
618604
return self.add_task(async_as_background(coro, silent=silent))
@@ -674,9 +660,7 @@ async def finish(self, exc_typ=None, exc=None, tb=None):
674660
async def _final(self):
675661
if self._cleaner:
676662
self._cleaner.cancel()
677-
await wait_for_all_futures(
678-
self._cleaner, name=f"TaskHolder({self.name})::finish[finally_wait_for_cleaner]"
679-
)
663+
await wait_for_all_futures(self._cleaner, name=f"TaskHolder({self.name})::finish[finally_wait_for_cleaner]")
680664

681665
await wait_for_all_futures(
682666
async_as_background(self.clean()),
@@ -708,9 +692,7 @@ async def clean(self):
708692
else:
709693
remaining.append(t)
710694

711-
await wait_for_all_futures(
712-
*destroyed, name=f"TaskHolder({self.name})::clean[wait_for_destroyed]"
713-
)
695+
await wait_for_all_futures(*destroyed, name=f"TaskHolder({self.name})::clean[wait_for_destroyed]")
714696
self.ts = remaining + [t for t in self.ts if t not in destroyed and t not in remaining]
715697

716698

@@ -841,19 +823,13 @@ def __repr__(self):
841823
status = "success" if self.successful else "failed"
842824
return f"<Result {status}: {self.value}: {self.context}>"
843825

844-
def __init__(
845-
self, final_future, *, error_catcher=None, exceptions_only_to_error_catcher=False, name=None
846-
):
826+
def __init__(self, final_future, *, error_catcher=None, exceptions_only_to_error_catcher=False, name=None):
847827
self.name = name
848-
self.final_future = ChildOfFuture(
849-
final_future, name=f"ResultStreamer({self.name})::__init__[final_future]"
850-
)
828+
self.final_future = ChildOfFuture(final_future, name=f"ResultStreamer({self.name})::__init__[final_future]")
851829
self.error_catcher = error_catcher
852830
self.exceptions_only_to_error_catcher = exceptions_only_to_error_catcher
853831

854-
self.queue_future = ChildOfFuture(
855-
final_future, name=f"ResultStreamer({self.name})::__init__[queue_future]"
856-
)
832+
self.queue_future = ChildOfFuture(final_future, name=f"ResultStreamer({self.name})::__init__[queue_future]")
857833
self.queue = Queue(
858834
self.queue_future,
859835
empty_on_finished=True,
@@ -896,9 +872,7 @@ async def run():
896872
task.gen = gen
897873

898874
if self.final_future.done():
899-
await cancel_futures_and_wait(
900-
task, name=f"ResultStreamer({self.name})::add_generator[already_stopped_task]"
901-
)
875+
await cancel_futures_and_wait(task, name=f"ResultStreamer({self.name})::add_generator[already_stopped_task]")
902876
await wait_for_first_future(
903877
async_as_background(gen.aclose()),
904878
name=f"ResultStreamer({self.name})::add_generator[already_stopped_gen]",
@@ -924,13 +898,9 @@ async def return_value():
924898
async def add_task(self, task, *, context=None, on_done=None, force=False):
925899
if self.final_future.done():
926900
if force:
927-
await wait_for_all_futures(
928-
task, name=f"ResultStreamer({self.name})::add_task[force_already_stopped]"
929-
)
901+
await wait_for_all_futures(task, name=f"ResultStreamer({self.name})::add_task[force_already_stopped]")
930902
else:
931-
await cancel_futures_and_wait(
932-
task, name=f"ResultStreamer({self.name})::add_task[already_stopped]"
933-
)
903+
await cancel_futures_and_wait(task, name=f"ResultStreamer({self.name})::add_task[already_stopped]")
934904
return task
935905

936906
def add_to_queue(res):
@@ -1296,9 +1266,7 @@ async def cancel_futures_and_wait(*futs, name=None):
12961266
fut.cancel()
12971267
waiting.append(fut)
12981268

1299-
await wait_for_all_futures(
1300-
*waiting, name=f"||cancel_futures_and_wait({name})[wait_for_everything]"
1301-
)
1269+
await wait_for_all_futures(*waiting, name=f"||cancel_futures_and_wait({name})[wait_for_everything]")
13021270

13031271

13041272
class memoized_property(tp.Generic[T]):
@@ -1339,7 +1307,7 @@ def __init__(self, func):
13391307
self.func = func
13401308
self.name = func.__name__
13411309
self.__doc__ = func.__doc__
1342-
self.cache_name = "_{0}".format(self.name)
1310+
self.cache_name = f"_{self.name}"
13431311

13441312
def __get__(self, instance: object = None, owner: object = None) -> T:
13451313
if instance is None:
@@ -1790,9 +1758,7 @@ def __init__(self, final_future, *, timeout=0.05, empty_on_finished=False, name=
17901758
self.name = name
17911759
self.timeout = timeout
17921760
self.collection = NormalQueue()
1793-
self.final_future = ChildOfFuture(
1794-
final_future, name=f"SyncQueue({self.name})::__init__[final_future]"
1795-
)
1761+
self.final_future = ChildOfFuture(final_future, name=f"SyncQueue({self.name})::__init__[final_future]")
17961762
self.empty_on_finished = empty_on_finished
17971763

17981764
def append(self, item):
@@ -1865,9 +1831,7 @@ def __init__(self, final_future, *, empty_on_finished=False, name=None):
18651831
self.name = name
18661832
self.waiter = ResettableFuture(name=f"Queue({self.name})::__init__[waiter]")
18671833
self.collection = deque()
1868-
self.final_future = ChildOfFuture(
1869-
final_future, name=f"Queue({self.name})::__init__[final_future]"
1870-
)
1834+
self.final_future = ChildOfFuture(final_future, name=f"Queue({self.name})::__init__[final_future]")
18711835
self.empty_on_finished = empty_on_finished
18721836

18731837
self.stop = False

modules/photons_app/mimic/__init__.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,13 @@
22
import os
33
import sys
44

5+
from photons_messages import Services, protocol_register
6+
from photons_transport.targets import LanTarget
7+
58
from photons_app import helpers as hp
69
from photons_app.mimic.device import Device
710
from photons_app.mimic.event import Events
811
from photons_app.mimic.transport import MemoryTarget
9-
from photons_messages import Services, protocol_register
10-
from photons_transport.targets import LanTarget
1112

1213
this_dir = os.path.dirname(__file__)
1314
for fle in os.listdir(os.path.join(this_dir, "operators")):
@@ -296,9 +297,7 @@ async def for_test(self, final_future, udp=False):
296297
for session in sessions:
297298
tt.append(ts.add(session.start()))
298299

299-
await hp.wait_for_all_futures(
300-
*tt, name="DeviceCollection::for_test[wait_for_start]"
301-
)
300+
await hp.wait_for_all_futures(*tt, name="DeviceCollection::for_test[wait_for_start]")
302301

303302
configuration = {
304303
"final_future": final_future,
@@ -328,9 +327,7 @@ async def for_test(self, final_future, udp=False):
328327
ends = []
329328
for session in sessions:
330329
ends.append(ts.add(session.finish(exc_typ=exc_typ, exc=exc, tb=tb)))
331-
await hp.wait_for_all_futures(
332-
*ends, name="DeviceCollection::for_test[wait_for_session_ends]"
333-
)
330+
await hp.wait_for_all_futures(*ends, name="DeviceCollection::for_test[wait_for_session_ends]")
334331

335332

336333
__all__ = ["Device", "DeviceCollection"]

0 commit comments

Comments
 (0)