[英]Pythonic way to pass a optional argument to a function: tweepy
I'm using the following tweepy function:我正在使用以下 tweepy function:
https://docs.tweepy.org/en/stable/client.html#search-tweets https://docs.tweepy.org/en/stable/client.html#search-tweets
For every request, it may return (or not) a param called next_token, that works like a pagination to start next request from where i stopped.对于每个请求,它可能返回(或不返回)一个名为 next_token 的参数,它的工作原理类似于分页,从我停止的位置开始下一个请求。
requests_list = []
tweets = client.search_all_tweets(query=query,
start_time=start_time,
end_time=end_time,
max_results=max_results,
expansions=expansions,
tweet_fields=tweet_fields,
user_fields=user_fields,
place_fields=place_fields)
requests_list.append(tweets)
while True:
if 'next_token' in tweets.meta:
tweets = client.search_all_tweets(query=query,
start_time=start_time,
end_time=end_time,
max_results=max_results,
expansions=expansions,
tweet_fields=tweet_fields,
user_fields=user_fields,
place_fields=place_fields,
next_token = tweets.meta['next_token'])
requests_list.append(tweets)
else:
break
So, what i did:所以,我做了什么:
How can i make it better (less code duplicated)?我怎样才能让它变得更好(重复的代码更少)?
Can i 'merge' the results (the same structure) instead of appending them into a list?我可以“合并”结果(相同的结构)而不是将它们附加到列表中吗?
You can use a dictionary to pass your arguments, something like this:您可以使用字典来传递您的 arguments,如下所示:
args = {'query':query,....}
flag = False
while True:
if (!flag or 'next_token' in tweets.meta):
if(flag):
args['next_token'] = tweets.meta['next_token']
tweets = client.search_all_tweets(**args)
flag = True
You can use argument unpacking to pass key work arguments to a function.您可以使用参数解包将密钥工作 arguments 传递给 function。
tweets = None # initial case
requests_list = []
next_token = None
while tweets is None or next_token:
kwargs = {}
if next_token:
kwargs['next_token'] = next_token
tweets = client.search_all_tweets(query=query,
start_time=start_time,
end_time=end_time,
max_results=max_results,
expansions=expansions,
tweet_fields=tweet_fields,
user_fields=user_fields,
place_fields=place_fields,
**kwargs)
requests_list.append(tweets)
next_token = tweets.meta.get('next_token')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.