11import ast
22import builtins
3+ import keyword
34import os
45import re
56import shutil
7+
68from custom_components .pyscript .const import FOLDER
79from custom_components .pyscript .state import STATE_VIRTUAL_ATTRS
8-
910from homeassistant .core import split_entity_id
1011from homeassistant .helpers import service as ha_service
1112from homeassistant .helpers .entity_registry import EntityRegistry
@@ -43,6 +44,9 @@ def get_or_create_cls(self, domain_id: str, base_class: str = "") -> ast.ClassDe
4344 self .domains [domain_id ] = domain
4445 return domain
4546
47+ def is_valid_identifier (self , identifier ) -> bool :
48+ return identifier .isidentifier () and not keyword .iskeyword (identifier )
49+
4650 def create_service (self , domain_id , service_id , service ):
4751 docstring = "\n " + self .DOCSTRING_INDENT
4852 docstring += service ["description" ]
@@ -57,6 +61,12 @@ def create_service(self, domain_id, service_id, service):
5761 if description is not None :
5862 docstring += f":param { field_name } : { description } \n { self .DOCSTRING_INDENT } "
5963
64+ if not self .is_valid_identifier (field_name ):
65+ fqn = f"{ domain_id } .{ service_id } ({ field_name } )"
66+ self .invalid_identifiers .append (fqn )
67+ log .warning (f"Invalid python identifier { fqn } " )
68+ continue
69+
6070 arg_annotation = None
6171 default_value = None
6272
@@ -164,7 +174,7 @@ def generate_services(self):
164174 if self .skip (fqn ):
165175 continue
166176 try :
167- if not service_id . isidentifier ( ):
177+ if not self . is_valid_identifier ( service_id ):
168178 self .invalid_identifiers .append (fqn )
169179 log .warning (f"Invalid python identifier { fqn } " )
170180 continue
@@ -182,7 +192,7 @@ def collect_atts(self, domain_id, entity_id):
182192 fqn = f"{ domain_id } .{ entity_id } .{ attr } "
183193 if self .skip (fqn ):
184194 continue
185- if not attr . isidentifier ( ):
195+ if not self . is_valid_identifier ( attr ):
186196 self .invalid_identifiers .append (fqn )
187197 log .warning (f"Invalid python identifier { fqn } " )
188198 continue
@@ -200,7 +210,7 @@ def generate_entities(self):
200210
201211 domain_id , entity_id = split_entity_id (entity .entity_id )
202212
203- if not entity_id . isidentifier ( ):
213+ if not self . is_valid_identifier ( entity_id ):
204214 self .invalid_identifiers .append (entity .entity_id )
205215 log .warning (f"Invalid python identifier { entity .entity_id } " )
206216 continue
0 commit comments