Skip to content

Commit

Permalink
draft of parameter conversion
Browse files Browse the repository at this point in the history
this isn't really exactly the right place: we only want to do this in the
IPC version of things, not the lazy.* version, since the lazy.* version
should just have users passing the right things, so this will result in a
bunch of extra useless work. but it's an example of parameter hoisting.

Signed-off-by: Tycho Andersen <[email protected]>
  • Loading branch information
tych0 committed Mar 17, 2024
1 parent 04354d5 commit c2bc5d3
Showing 1 changed file with 39 additions and 2 deletions.
41 changes: 39 additions & 2 deletions libqtile/command/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,9 @@
import inspect
import sys
import traceback
import types
from functools import partial
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, get_origin, get_args

from libqtile.configurable import Configurable
from libqtile.log_utils import logger
Expand Down Expand Up @@ -74,7 +75,43 @@ def wrapper(func: Callable):
func._mapping.append(name) # type:ignore
else:
logger.error("Unexpected value received in command decorator: %s", name)
return func

def lift_arg(typ, arg):
# for stuff like int | None, allow either
if get_origin(typ) is types.UnionType:
for t in get_args(typ):
if t == types.NoneType:
# special case None? I don't know what this looks like
# coming over IPC
if arg == "":
return None
if arg == None:
return None
continue

try:
return lift_arg(t, arg)
except TypeError:
pass
# uh oh, we couldn't lift it to anything
raise TypeError(f"{arg} is not a {typ}")
return typ(arg)

def type_converter(*args, **kwargs):
converted_args = []
converted_kwargs = dict()

params = inspect.signature(func).parameters

for arg, param in zip(args, params):
converted_args.append(lift_arg(param.annotation, arg))

for k, v in kwargs:
converted_kwargs[k] = lift_arg(params[k].annotation, v)

return func(*converted_args, **converted_kwargs)

return type_converter

# If the decorator is added with no parentheses then we should treat it
# as if it had been i.e. expose the decorated method
Expand Down

0 comments on commit c2bc5d3

Please sign in to comment.