Skip to content

Commit 8834344

Browse files
committed
Optional Typing support
1 parent 5e42567 commit 8834344

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

src/Rules.py

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -283,9 +283,19 @@ def convert_req_function_args(func, args: list[str], areaName: str, warn: bool =
283283
continue
284284

285285
argType = info.annotation
286+
optional = False
287+
try:
288+
if issubclass(argType, inspect._empty): #if not set then it wont get converted but still be checked for valid data at index
289+
argType = str
286290

287-
if issubclass(argType, inspect._empty): #if not set then it wont get converted but still be checked for valid data at index
288-
argType = str
291+
except TypeError: # Optional
292+
if argType.__module__ == 'typing' and argType._name == 'Optional':
293+
optional = True
294+
argType = argType.__args__[0]
295+
else:
296+
#Implementing complex typing is not simple so ill skip it for now
297+
index += 1
298+
continue
289299

290300
try:
291301
value = args[index].strip()
@@ -297,6 +307,17 @@ def convert_req_function_args(func, args: list[str], areaName: str, warn: bool =
297307
else:
298308
raise Exception(f"A call of the {func.__name__} function in '{areaName}'s requirement, asks for a value of type {argType}\nfor its argument '{info.name}' but its missing")
299309

310+
if optional:
311+
if isinstance(value, type(None)):
312+
index += 1
313+
continue
314+
elif isinstance(value, str):
315+
if value.lower() == 'none':
316+
value = None
317+
args[index] = value
318+
index += 1
319+
continue
320+
300321

301322
if not isinstance(value, argType):
302323
if issubclass(argType, bool):
@@ -313,7 +334,6 @@ def convert_req_function_args(func, args: list[str], areaName: str, warn: bool =
313334
# warning here spam the console if called from rules.py, might be worth to make it a data validation instead
314335
logging.warn(f"A call of the {func.__name__} function in '{areaName}'s requirement, asks for a value of type {argType}\nfor its argument '{info.name}' but an unknown string was passed and thus converted to {value}")
315336

316-
317337
else:
318338
try:
319339
value = argType(value)

0 commit comments

Comments
 (0)