Skip to content

Instantly share code, notes, and snippets.

@Devwarlt
Last active August 11, 2021 21:07
Show Gist options
  • Save Devwarlt/2f4eba5b74dc332f288b23c8f110db56 to your computer and use it in GitHub Desktop.
Save Devwarlt/2f4eba5b74dc332f288b23c8f110db56 to your computer and use it in GitHub Desktop.
Unpack Sorted: This is a cool feature to use if you don't mind about sending bunch of arguments to a method. Use it wisely!
# Author: Devwarlt
# Date: 11 Aug 2021
#
# About this algorithm:
# This is a cool feature to use if you don't mind
# about sending bunch of arguments to a method.
# Use it wisely!
#
# Sample class for testing purposes-only.
class Test(object):
def __init__(self, arg_1: int, arg_2: str, arg_3: object) -> None:
super().__init__()
self.__arg_1: int = arg_1
self.__arg_2: str = arg_2
self.__arg_3: object = arg_3
@property
def arg_1(self) -> int:
return self.__arg_1
@property
def arg_2(self) -> str:
return self.__arg_2
@property
def arg_3(self) -> object:
return self.__arg_3
def __get_str_info(self, arg: object) -> str:
return arg.__str__() if arg else "null"
def __str__(self) -> str:
args: list = [
"arg_1: " + self.__get_str_info(self.arg_1),
"arg_2: " + self.__get_str_info(self.arg_2),
"arg_3: " + self.__get_str_info(self.arg_3)
]
return ",\n".join(args)
from typing import (
Callable, Iterable, Any,
List, Tuple, Union
)
def unpack_sorted(
statement: Callable[..., Any],
*args: Iterable[
Union[
List[Any],
Tuple[Any]
]
]
) -> Union[Any, None]:
try:
statement_sig: signature = signature(statement)
count_params: int =\
statement_sig.parameters.__len__()
sorted_args: List[Any] = []
sorted_args += args
sorted_args += [
None for i in range(
count_params - args.__len__()
)
]
callback: Any = statement(*sorted_args)
return callback
except:
msg: str = "Unable to unpack sorted arguments, "\
"because there is no signature for statement "\
f"'{statement.__name__}'!"
warn(msg, category=RuntimeWarning)
return None
test: Test = Test(1, "2", 3)
print(test)
# Throws a RuntimeWarning warning and return a
# null value from callback:
print(unpack_sorted(print, 9, 2))
# Returns a new instance of 'Test' class:
print(unpack_sorted(Test, 9, 2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment