Reputation: 307
guys below is my code for dictionary generating:
import collections
from typing import Callable
def group_by_retval(*args, grouper_func: Callable[[], None]):
my_list = []
for elem in args:
my_tr = grouper_func(elem)
my_list.append([my_tr,elem])
my_tuple = tuple(tuple(elem) for elem in my_list)
my_diction = collections.defaultdict(list)
for k,v in my_tuple:
my_diction[k].append(v)
return my_diction
I have read from python official documentation that I can announce callable function after the *args. as above. However, when I run simple example like below I got an error. Can someone please help me to solve this issue. Thank you for reading:
l = ["ab", 12, "cd", "d", 3]
print(group_by_retval(l, lambda x: isinstance(x, str)))
Upvotes: 0
Views: 633
Reputation: 5070
As mentioned in comments, after *arg
(arbitrary arguments list) you could use only keyword arguments:
group_by_retval(l, grouper_func=lambda x: isinstance(x, str))
to do it without providing a name you could swap arguments:
def group_by_retval(grouper_func: Callable[[], None], *args):
...
print(group_by_retval(lambda x: isinstance(x, str), l))
Output:
defaultdict(<class 'list'>, {False: [['ab', 12, 'cd', 'd', 3]]})
But in fact, you just do not need to use arbitrary arguments list, because your first argument is a list
. Right solution
def group_by_retval(args, grouper_func: Callable[[], None]):
...
print(group_by_retval(l, lambda x: isinstance(x, str)))
Output:
defaultdict(<class 'list'>, {False: [12, 3], True: ['ab', 'cd', 'd']})
Upvotes: 1