سؤال

I'm trying to pass an arbitrary number of arguments to a function, and I keep getting errors, and not quite sure where I'm going wrong. This is the first time I've attempted to use **kwargs.

More specifically, I'm trying to use the Facepy library to get data from Facebook's Graph API. According to the documentation (https://facepy.readthedocs.org/en/latest/usage/graph-api.html), the get method should accept optional parameters like "since", "until", etc. Since I only want to pass some of these parameters on any given query, this seems like an ideal time to use **kwargs.

First I create a function that wraps the Facepy library:

def graph_retriever(object_id, metric_url, **kwargs): 
    #optional args that I want to pass include since, until, and summary
    graph = facepy.GraphAPI(access_token)
    retries = 3 # An integer describing how many times the request may be retried.
    object_data = graph.get('%s/%s' % (object_id, metric_url), False, retries, **kwargs)
    return object_data

Here's two examples where I call the function with different arguments:

for since, until in day_segmenter(start, end): # loop through the date range
    raw_post_data = graph_retriever(str(page), 'posts', {'since': since, 'until': until})

post_dict['comment_count'] = graph_retriever(post_id, 'comments', {'summary':1})['summary']['total_count']

However, when I try to run this, I get the following error:

Traceback (most recent call last): raw_post_data = graph_retriever(str(page), 'posts', {'since': since, 'until': until}) TypeError: graph_retriever() takes exactly 2 arguments (3 given)

What am I doing wrong?

هل كانت مفيدة؟

المحلول

يمكنك تمرير قاموس مثل Kwargs عن طريق تفريغه باستخدام **

graph_retriever(str(page), 'posts', **{'since': since, 'until': until})

تحرير 1:

يجب أن يتم تمرير kwargs بالفعل ككلمة رئيسية ، أي يجب أن تسمى الوظيفة باسم

graph_retriever(str(page), 'posts', since= since, until= until)

انظر هنا للحصول على المستندات بيثون كوارج

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top