@@ -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 ):
0 commit comments