Skip to content

Commit

Permalink
Added decorator to allow functions which expect a single tuple (or li…
Browse files Browse the repository at this point in the history
…st) to accept starred non-keyword arguments
  • Loading branch information
timbernat committed Apr 22, 2024
1 parent a4a70a7 commit b8413a9
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion polymerist/genutils/decorators/functional.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'''Decorators for modifying functions'''

from typing import Callable, Optional, Union
from typing import Callable, Iterable, Optional, Type, Union

import inspect
from functools import wraps
Expand Down Expand Up @@ -49,6 +49,24 @@ def in_place_wrapper(obj : object, *args : Args, in_place : bool=False, **kwargs

return in_place_wrapper

@extend_to_methods
def flexible_tuple_input(func : Callable[[tuple], T], valid_types : Union[Type, tuple[Type]]=object) -> Callable[[Iterable], T]:
'''Wrapper which allows a function which expects a single tuple to accept Iterable or even star-unpacked arguments'''
@wraps(func)
def wrapper(*args) -> T: # wrapper which accepts an arbitrary number of non-keyword argument
if (len(args) == 1) and isinstance(args[0], Iterable):
args = args[0]

inputs = []
for value in args:
if isinstance(value, valid_types): # works because isinstance() accepts either a single type or a tuple of types
inputs.append(value)
else:
raise TypeError
return func(inputs) # TODO: modify input type signature of wrapper function

return wrapper

@extend_to_methods
def allow_string_paths(funct : Callable[[Path, Args, KWArgs], T]) -> Callable[[Union[Path, str], Args, KWArgs], T]:
'''Modifies a function which expects a Path as its first argument to also accept string-paths'''
Expand Down

0 comments on commit b8413a9

Please sign in to comment.