Skip to content

Commit f5816d1

Browse files
committed
set line-length to 109 for black/flake8/isort
1 parent 2a59fc8 commit f5816d1

File tree

15 files changed

+168
-560
lines changed

15 files changed

+168
-560
lines changed

custom_components/pyscript/__init__.py

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,7 @@
3030
CONF_ALLOW_ALL_IMPORTS = "allow_all_imports"
3131

3232
CONFIG_SCHEMA = vol.Schema(
33-
{
34-
DOMAIN: vol.Schema(
35-
{vol.Optional(CONF_ALLOW_ALL_IMPORTS, default=False): cv.boolean}
36-
),
37-
},
33+
{DOMAIN: vol.Schema({vol.Optional(CONF_ALLOW_ALL_IMPORTS, default=False): cv.boolean})},
3834
extra=vol.ALLOW_EXTRA,
3935
)
4036

@@ -66,9 +62,7 @@ def check_isdir(path):
6662

6763
async def reload_scripts_handler(call):
6864
"""Handle reload service calls."""
69-
_LOGGER.debug(
70-
"stopping triggers and services, reloading scripts, and restarting"
71-
)
65+
_LOGGER.debug("stopping triggers and services, reloading scripts, and restarting")
7266

7367
ctx_delete = {}
7468
for global_ctx_name, global_ctx in GlobalContextMgr.items():
@@ -110,9 +104,7 @@ def state_var_remove():
110104

111105
kernel.set_session_cleanup_callback(state_var_remove)
112106

113-
hass.services.async_register(
114-
DOMAIN, SERVICE_JUPYTER_KERNEL_START, jupyter_kernel_start
115-
)
107+
hass.services.async_register(DOMAIN, SERVICE_JUPYTER_KERNEL_START, jupyter_kernel_start)
116108

117109
async def state_changed(event):
118110
var_name = event.data["entity_id"]

custom_components/pyscript/eval.py

Lines changed: 25 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -202,9 +202,7 @@ async def eval_defaults(self, ast_ctx):
202202
self.num_posn_arg = len(self.func_def.args.args) - len(self.defaults)
203203
self.kw_defaults = []
204204
for val in self.func_def.args.kw_defaults:
205-
self.kw_defaults.append(
206-
{"ok": bool(val), "val": None if not val else await ast_ctx.aeval(val)}
207-
)
205+
self.kw_defaults.append({"ok": bool(val), "val": None if not val else await ast_ctx.aeval(val)})
208206

209207
async def eval_decorators(self, ast_ctx):
210208
"""Evaluate the function decorators arguments."""
@@ -225,9 +223,7 @@ async def eval_decorators(self, ast_ctx):
225223
elif isinstance(dec, ast.Name):
226224
self.decorators.append([dec.id, None, None])
227225
else:
228-
_LOGGER.error(
229-
"function %s has unexpected decorator type %s", self.name, dec
230-
)
226+
_LOGGER.error("function %s has unexpected decorator type %s", self.name, dec)
231227

232228
def get_decorators(self):
233229
"""Return the function decorators."""
@@ -252,9 +248,7 @@ async def try_aeval(self, ast_ctx, arg):
252248
raise
253249
except Exception as err: # pylint: disable=broad-except
254250
if ast_ctx.exception_long is None:
255-
ast_ctx.exception_long = ast_ctx.format_exc(
256-
err, arg.lineno, arg.col_offset
257-
)
251+
ast_ctx.exception_long = ast_ctx.format_exc(err, arg.lineno, arg.col_offset)
258252

259253
async def call(self, ast_ctx, args=None, kwargs=None):
260254
"""Call the function with the given context and arguments."""
@@ -268,9 +262,7 @@ async def call(self, ast_ctx, args=None, kwargs=None):
268262
if i < len(args):
269263
val = args[i]
270264
if var_name in kwargs:
271-
raise TypeError(
272-
f"{self.name}() got multiple values for argument '{var_name}'"
273-
)
265+
raise TypeError(f"{self.name}() got multiple values for argument '{var_name}'")
274266
elif var_name in kwargs:
275267
val = kwargs[var_name]
276268
del kwargs[var_name]
@@ -289,17 +281,13 @@ async def call(self, ast_ctx, args=None, kwargs=None):
289281
elif i < len(self.kw_defaults) and self.kw_defaults[i]["ok"]:
290282
val = self.kw_defaults[i]["val"]
291283
else:
292-
raise TypeError(
293-
f"{self.name}() missing required keyword-only arguments"
294-
)
284+
raise TypeError(f"{self.name}() missing required keyword-only arguments")
295285
sym_table[var_name] = val
296286
if self.func_def.args.kwarg:
297287
sym_table[self.func_def.args.kwarg.arg] = kwargs
298288
if self.func_def.args.vararg:
299289
if len(args) > len(self.func_def.args.args):
300-
sym_table[self.func_def.args.vararg.arg] = tuple(
301-
args[len(self.func_def.args.args) :]
302-
)
290+
sym_table[self.func_def.args.vararg.arg] = tuple(args[len(self.func_def.args.args) :])
303291
else:
304292
sym_table[self.func_def.args.vararg.arg] = ()
305293
elif len(args) > len(self.func_def.args.args):
@@ -354,9 +342,7 @@ def __init__(self, name, global_ctx, logger_name=None):
354342
self.logger = None
355343
self.set_logger_name(logger_name if logger_name is not None else self.name)
356344
self.allow_all_imports = (
357-
global_ctx.hass.data[DOMAIN]["allow_all_imports"]
358-
if global_ctx.hass is not None
359-
else False
345+
global_ctx.hass.data[DOMAIN]["allow_all_imports"] if global_ctx.hass is not None else False
360346
)
361347

362348
async def ast_not_implemented(self, arg, *args):
@@ -401,9 +387,7 @@ async def ast_import(self, arg):
401387
if not self.allow_all_imports and imp.name not in ALLOWED_IMPORTS:
402388
raise ModuleNotFoundError(f"import of {imp.name} not allowed")
403389
if imp.name not in sys.modules:
404-
mod = await Function.hass.async_add_executor_job(
405-
importlib.import_module, imp.name
406-
)
390+
mod = await Function.hass.async_add_executor_job(importlib.import_module, imp.name)
407391
else:
408392
mod = sys.modules[imp.name]
409393
self.sym_table[imp.name if imp.asname is None else imp.asname] = mod
@@ -413,9 +397,7 @@ async def ast_importfrom(self, arg):
413397
if not self.allow_all_imports and arg.module not in ALLOWED_IMPORTS:
414398
raise ModuleNotFoundError(f"import from {arg.module} not allowed")
415399
if arg.module not in sys.modules:
416-
mod = await Function.hass.async_add_executor_job(
417-
importlib.import_module, arg.module
418-
)
400+
mod = await Function.hass.async_add_executor_job(importlib.import_module, arg.module)
419401
else:
420402
mod = sys.modules[arg.module]
421403
for imp in arg.names:
@@ -424,9 +406,7 @@ async def ast_importfrom(self, arg):
424406
if name[0] != "_":
425407
self.sym_table[name] = value
426408
else:
427-
self.sym_table[
428-
imp.name if imp.asname is None else imp.asname
429-
] = getattr(mod, imp.name)
409+
self.sym_table[imp.name if imp.asname is None else imp.asname] = getattr(mod, imp.name)
430410

431411
async def ast_if(self, arg):
432412
"""Execute if statement."""
@@ -529,10 +509,7 @@ async def ast_functiondef(self, arg):
529509
async def ast_lambda(self, arg):
530510
"""Evaluate lambda definition."""
531511
funcdef = ast.FunctionDef(
532-
args=arg.args,
533-
body=[ast.Return(value=arg.body)],
534-
name="lambda",
535-
decorator_list=None,
512+
args=arg.args, body=[ast.Return(value=arg.body)], name="lambda", decorator_list=None,
536513
)
537514
func = EvalFunc(funcdef, self.code_list, self.code_str)
538515
await func.eval_defaults(self)
@@ -651,9 +628,7 @@ async def ast_with(self, arg, async_attr=""):
651628
)
652629
for ctx in ctx_list:
653630
if ctx["target"]:
654-
value = await self.call_func(
655-
ctx["enter"], enter_attr, [ctx["manager"]], {}
656-
)
631+
value = await self.call_func(ctx["enter"], enter_attr, [ctx["manager"]], {})
657632
await self.recurse_assign(ctx["target"], value)
658633
for arg1 in arg.body:
659634
val = await self.aeval(arg1)
@@ -663,18 +638,14 @@ async def ast_with(self, arg, async_attr=""):
663638
hit_except = True
664639
exit_ok = True
665640
for ctx in reversed(ctx_list):
666-
ret = await self.call_func(
667-
ctx["exit"], exit_attr, [ctx["manager"], *sys.exc_info()], {}
668-
)
641+
ret = await self.call_func(ctx["exit"], exit_attr, [ctx["manager"], *sys.exc_info()], {})
669642
exit_ok = exit_ok and ret
670643
if not exit_ok:
671644
raise
672645
finally:
673646
if not hit_except:
674647
for ctx in reversed(ctx_list):
675-
await self.call_func(
676-
ctx["exit"], exit_attr, [ctx["manager"], None, None, None], {}
677-
)
648+
await self.call_func(ctx["exit"], exit_attr, [ctx["manager"], None, None, None], {})
678649
return val
679650

680651
async def ast_asyncwith(self, arg):
@@ -720,9 +691,7 @@ async def recurse_assign(self, lhs, val):
720691
try:
721692
vals = [*(val.__iter__())]
722693
except Exception: # pylint: disable=broad-except
723-
raise TypeError(
724-
"cannot unpack non-iterable object"
725-
) # pylint: disable=raise-missing-from
694+
raise TypeError("cannot unpack non-iterable object") # pylint: disable=raise-missing-from
726695
got_star = 0
727696
for lhs_elt in lhs.elts:
728697
if isinstance(lhs_elt, ast.Starred):
@@ -735,17 +704,14 @@ async def recurse_assign(self, lhs, val):
735704
err_msg = f"{len(lhs.elts)}"
736705
raise ValueError(f"too few values to unpack (expected {err_msg})")
737706
if len(lhs.elts) < len(vals) and got_star == 0:
738-
raise ValueError(
739-
f"too many values to unpack (expected {len(lhs.elts)})"
740-
)
707+
raise ValueError(f"too many values to unpack (expected {len(lhs.elts)})")
741708
val_idx = 0
742709
for lhs_elt in lhs.elts:
743710
if isinstance(lhs_elt, ast.Starred):
744711
star_len = len(vals) - len(lhs.elts) + 1
745712
star_name = lhs_elt.value.id
746713
await self.recurse_assign(
747-
ast.Name(id=star_name, ctx=ast.Store()),
748-
vals[val_idx : val_idx + star_len],
714+
ast.Name(id=star_name, ctx=ast.Store()), vals[val_idx : val_idx + star_len],
749715
)
750716
val_idx += star_len
751717
else:
@@ -767,9 +733,7 @@ async def recurse_assign(self, lhs, val):
767733
var_name.setattr(val)
768734
return
769735
if not isinstance(var_name, str):
770-
raise NotImplementedError(
771-
f"unknown lhs type {lhs} (got {var_name}) in assign"
772-
)
736+
raise NotImplementedError(f"unknown lhs type {lhs} (got {var_name}) in assign")
773737
if var_name.find(".") >= 0:
774738
State.set(var_name, val)
775739
return
@@ -793,9 +757,7 @@ async def ast_assign(self, arg):
793757
async def ast_augassign(self, arg):
794758
"""Execute augmented assignment statement (lhs <BinOp>= value)."""
795759
arg.target.ctx = ast.Load()
796-
new_val = await self.aeval(
797-
ast.BinOp(left=arg.target, op=arg.op, right=arg.value)
798-
)
760+
new_val = await self.aeval(ast.BinOp(left=arg.target, op=arg.op, right=arg.value))
799761
arg.target.ctx = ast.Store()
800762
await self.recurse_assign(arg.target, new_val)
801763

@@ -824,9 +786,7 @@ async def ast_delete(self, arg):
824786
step = await self.aeval(arg1.slice.step)
825787
del var[slice(lower, upper, step)]
826788
else:
827-
raise NotImplementedError(
828-
f"{self.name}: not implemented slice type {arg1.slice} in del"
829-
)
789+
raise NotImplementedError(f"{self.name}: not implemented slice type {arg1.slice} in del")
830790
elif isinstance(arg1, ast.Name):
831791
if self.curr_func and arg1.id in self.curr_func.global_names:
832792
if arg1.id in self.global_sym_table:
@@ -912,11 +872,7 @@ async def ast_name(self, arg):
912872
return self.global_sym_table[arg.id]
913873
if arg.id in BUILTIN_AST_FUNCS_FACTORY:
914874
return BUILTIN_AST_FUNCS_FACTORY[arg.id](self)
915-
if (
916-
hasattr(builtins, arg.id)
917-
and arg.id not in BUILTIN_EXCLUDE
918-
and arg.id[0] != "_"
919-
):
875+
if hasattr(builtins, arg.id) and arg.id not in BUILTIN_EXCLUDE and arg.id[0] != "_":
920876
return getattr(builtins, arg.id)
921877
if Function.get(arg.id):
922878
return Function.get(arg.id)
@@ -1205,9 +1161,7 @@ async def ast_call(self, arg):
12051161
else:
12061162
kwargs[kw_arg.arg] = await self.aeval(kw_arg.value)
12071163
args = await self.eval_elt_list(arg.args)
1208-
arg_str = ", ".join(
1209-
['"' + elt + '"' if isinstance(elt, str) else str(elt) for elt in args]
1210-
)
1164+
arg_str = ", ".join(['"' + elt + '"' if isinstance(elt, str) else str(elt) for elt in args])
12111165
#
12121166
# try to deduce function name, although this only works in simple cases
12131167
#
@@ -1240,11 +1194,7 @@ async def call_func(self, func, func_name, args, kwargs):
12401194

12411195
async def ast_ifexp(self, arg):
12421196
"""Evaluate if expression."""
1243-
return (
1244-
await self.aeval(arg.body)
1245-
if (await self.aeval(arg.test))
1246-
else await self.aeval(arg.orelse)
1247-
)
1197+
return await self.aeval(arg.body) if (await self.aeval(arg.test)) else await self.aeval(arg.orelse)
12481198

12491199
async def ast_num(self, arg):
12501200
"""Evaluate number."""
@@ -1430,9 +1380,7 @@ def completions(self, root):
14301380
var = self.global_sym_table[name]
14311381
try:
14321382
for attr in var.__dir__():
1433-
if attr.lower().startswith(attr_root) and (
1434-
attr_root != "" or attr[0:1] != "_"
1435-
):
1383+
if attr.lower().startswith(attr_root) and (attr_root != "" or attr[0:1] != "_"):
14361384
value = getattr(var, attr, None)
14371385
if callable(value) or isinstance(value, EvalFunc):
14381386
words.add(f"{name}.{attr}")
@@ -1474,9 +1422,7 @@ async def eval(self, new_state_vars=None):
14741422
raise
14751423
except Exception as err: # pylint: disable=broad-except
14761424
if self.exception_long is None:
1477-
self.exception_long = self.format_exc(
1478-
err, self.lineno, self.col_offset
1479-
)
1425+
self.exception_long = self.format_exc(err, self.lineno, self.col_offset)
14801426
return None
14811427

14821428
def dump(self):

custom_components/pyscript/event.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,7 @@ def notify_add(cls, event_type, queue):
5050
if event_type not in cls.notify:
5151
cls.notify[event_type] = set()
5252
_LOGGER.debug("event.notify_add(%s) -> adding event listener", event_type)
53-
cls.notify_remove[event_type] = cls.hass.bus.async_listen(
54-
event_type, cls.event_listener
55-
)
53+
cls.notify_remove[event_type] = cls.hass.bus.async_listen(event_type, cls.event_listener)
5654
cls.notify[event_type].add(queue)
5755

5856
@classmethod

custom_components/pyscript/function.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -122,9 +122,7 @@ async def task_executor(cls, func, *args, **kwargs):
122122
"""Implement task.executor()."""
123123
if asyncio.iscoroutinefunction(func) or not callable(func):
124124
raise TypeError("function is not callable by task.executor()")
125-
return await cls.hass.async_add_executor_job(
126-
functools.partial(func, **kwargs), *args
127-
)
125+
return await cls.hass.async_add_executor_job(functools.partial(func, **kwargs), *args)
128126

129127
@classmethod
130128
def unique_name_used(cls, name):
@@ -150,11 +148,7 @@ async def service_completions(cls, root):
150148
if num_period == 1:
151149
domain, svc_root = root.split(".")
152150
if domain in services:
153-
words |= {
154-
f"{domain}.{svc}"
155-
for svc in services[domain]
156-
if svc.lower().startswith(svc_root)
157-
}
151+
words |= {f"{domain}.{svc}" for svc in services[domain] if svc.lower().startswith(svc_root)}
158152
elif num_period == 0:
159153
words |= {domain for domain in services if domain.lower().startswith(root)}
160154

custom_components/pyscript/global_ctx.py

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -96,16 +96,11 @@ async def trigger_init(self, func):
9696
try:
9797
desc = desc[4:].lstrip(" \n\r")
9898
file_desc = io.StringIO(desc)
99-
service_desc = (
100-
yaml.load(file_desc, Loader=yaml.BaseLoader)
101-
or OrderedDict()
102-
)
99+
service_desc = yaml.load(file_desc, Loader=yaml.BaseLoader) or OrderedDict()
103100
file_desc.close()
104101
except Exception as exc:
105102
self.logger.error(
106-
"Unable to decode yaml doc_string for %s(): %s",
107-
func_name,
108-
str(exc),
103+
"Unable to decode yaml doc_string for %s(): %s", func_name, str(exc),
109104
)
110105
raise exc
111106
else:
@@ -145,10 +140,7 @@ async def do_service_call(func, ast_ctx, data):
145140
self.services.add(func_name)
146141
else:
147142
self.logger.warning(
148-
"%s defined in %s: unknown decorator @%s: ignored",
149-
func_name,
150-
self.name,
151-
dec_name,
143+
"%s defined in %s: unknown decorator @%s: ignored", func_name, self.name, dec_name,
152144
)
153145

154146
if func_name in self.services and "service" not in decorator_used:
@@ -251,9 +243,7 @@ async def do_service_call(func, ast_ctx, data):
251243
if func_name in self.triggers:
252244
await self.triggers[func_name].stop()
253245

254-
self.triggers_new[func_name] = TrigInfo(
255-
f"{self.name}.{func_name}", trig_args, global_ctx=self,
256-
)
246+
self.triggers_new[func_name] = TrigInfo(f"{self.name}.{func_name}", trig_args, global_ctx=self,)
257247

258248
if self.auto_start:
259249
await self.start()

0 commit comments

Comments
 (0)