简体   繁体   中英

How to pass parameters to function via variable?

i am executing function in separate thread and want to pass arguments via queue. So function should be idealy able to accept all variables encapsulated in one variable

something like:

v = ('arg1', kwarg1='val1', kwarg2='val2')

def print_arg(*args, **kwargs):
    print('args:{}\nkwargs:{}'.format(args, kwargs))

print_arg(v)

Is there any simple way how to achieve this?

Thanks

One way for you to do this may be to build the queue in your main thread and pass it as an argument to the thread you create:

q = queue.Queue()   
thread1 = threading.Thread(target=main_function,args(q,other_args)) 

In either thread, use the put method to add information to the queue as strings:

q.put(str(important_variable))

Retrieve this information from the queue with the get method

important_variable = q.get()

If passing multiple variables or information, use multiple queues or structure what you put into the queue so that you know what it is you're pulling out of the queue.

While yes, you can store all arguments in a single variable, you still need to store the positional arguments separately from the keyword arguments. There is no data structure that can function as a sequence and a mapping at the same time.

Here's one way to do it:

v = ['arg1'], {'kwarg1': 'val1', 'kwarg2': 'val2'}
print_arg(*v[0], **v[1])

This is a bit tedious and hard to read, so we can encapsulate the whole thing in a class:

class ArgumentBundle:
    def __init__(self, *args, **kwargs):
        self.args = args
        self.kwargs = kwargs

    def call(self, function):
        return function(*self.args, **self.kwargs)

v = ArgumentBundle('arg1', kwarg1='val1', kwarg2='val2')
v.call(print_arg)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM