在Python文档字符串中,如何记录:rtype:可以返回多种可能数据类型的函数?
例如,如果函数可以返回defaultdictOR dictOR list,则根据函数参数,您如何记录这个?
代码示例:
from collections import defaultdict
def read_state(state_file, state_file_type='defaultdict'):
"""Deserialize state file or create empty state and return it.
:param state_file: The path and file name of state file to read.
:type state_file: str
:param state_file_type: Data type in which state is stored.
:type state_file_type: str
:return: Current or new empty state.
:rtype: ?????
"""
if os.path.exists(state_file):
with open(state_file) as conf_fo:
state = json.load(conf_fo)
elif state_file_type == 'defaultdict':
state = defaultdict(lambda: …Run Code Online (Sandbox Code Playgroud) 我有一个熊猫DataFrame,其中包含一列,其中包含多个JSON数据项作为字典列表。我想规范化JSON列并复制非JSON列:
# creating dataframe
df_actions = pd.DataFrame(columns=['id', 'actions'])
rows = [[12,json.loads('[{"type": "a","value": "17"},{"type": "b","value": "19"}]')],
[15, json.loads('[{"type": "a","value": "1"},{"type": "b","value": "3"},{"type": "c","value": "5"}]')]]
df_actions.loc[0] = rows[0]
df_actions.loc[1] = rows[1]
>>>df_actions
id actions
0 12 [{'type': 'a', 'value': '17'}, {'type': 'b', '...
1 15 [{'type': 'a', 'value': '1'}, {'type': 'b', 'v...
Run Code Online (Sandbox Code Playgroud)
我想要
>>>df_actions_parsed
id type value
12 a 17
12 b 19
15 a 1
15 b 3
15 c 5
Run Code Online (Sandbox Code Playgroud)
我可以使用以下方式标准化JSON数据:
pd.concat([pd.DataFrame(json_normalize(x)) for x in df_actions['actions']],ignore_index=True)
Run Code Online (Sandbox Code Playgroud)
但我不知道如何将其重新连接到原始DataFrame的id列。
我们正在通过 Facebook 营销 API 检索洞察数据。为此,我们正在使用 Python 的“facebookads”模块。我过去一直在下载我们所有帐户的历史数据,这些数据运行良好。自 2 周左右以来,我收到此错误:
2018-06-01 16:01:57 - (DEBUG) - urllib3.connectionpool - https://graph.facebook.com:443 "GET /v2.11/act_nnnn/insights?access_token=&appsecret_proof=&time_range=%7B% 22since%22%3A%222018-05-08%22%2C%22until%22%3A%222018-05-08%22%7D&level=ad&breakdowns=%5B%22impression_device%22%5D&filtering=%5B%7B% 22%3A%22spend%22%2C%22operator%22%3A%22GREATER_THAN%22%2C%22value%22%3A%220%22%7D%5D&limit=5000&fields=account_id%2Ccampaign_id%2Ccampaign_id%2Ccampaign_id%2Ccampaign_id%2Ccampaign_id%2Ccampaign_id%2Ccampaign_id%2Ccampaign_id%2Ccampaign%2Ccampaign%22%2C%22value%22%3A%220%22%7D%5D 2Cad_name%2Cimpressions%2Cclicks%2Creach%2Cspend%2Caccount_currency%2Cactions%2Caction_values%2Ctotal_actions%2Ctotal_action_value HTTP/1.1" 500 77
2018-06-01 16:01:57 - (DEBUG) - FacebookAdsDownloader - 发生异常:
消息:调用不成功
方法:获取
路径:https : //graph.facebook.com/v2.11/act_nnnn/insights
参数: {'time_range': '{"since":"2018-05-08","until":"2018-05-08"}', 'level': 'ad', 'breakdowns': '[" impress_device"]', 'filtering': '[{"field":"spend","operator":"GREATER_THAN","value":"0"}]', 'limit': 5000, 'fields': ' account_id、campaign_id、campaign_name、adset_id、adset_name、ad_id、ad_name、展示次数、点击次数、覆盖面、支出、account_currency、动作、action_values、total_actions、total_action_value'}
状态:500
响应:{ "error": { "code": 1, "message": "发生未知错误", "error_subcode": 99 } }
任何人都有想法,为什么我会收到此错误?这个完全相同的请求已经在起作用了。我一遍又一遍地重试相同的请求。
我希望有一个带有方法的调度程序dict {str:method}.我想迭代调度程序键并将值作为方法调用,但是当我运行Python脚本时,一旦创建了dict,方法就会被执行:
from python.helper.my_client import Client
def deco_download(f):
def f_download(*args, **kwargs):
# some retry functionality here
return json_data
return f_download
class Downloader:
def __init__(self):
self.attribute = 'some_value'
@deco_download
def download_persons(self, client, *args, **kwargs):
return client.get_persons(*args, **kwargs)
@deco_download
def download_organizations(self, client, *args, **kwargs):
return client.get_organizations(*args, **kwargs)
def run(self):
dispatcher = {
'person': self.download_persons(client),
'organization': self.download_organizations(client)
}
for key in dispatcher:
print("Downlading data for: {0}".format(key)
dispatcher[key]
Run Code Online (Sandbox Code Playgroud)
不幸的是,在我在for循环中调用它们之前初始化调度程序dict时,这些方法是直接执行的.我希望它们可以在for循环中调用,而不是在dict构造期间调用.我在这做错了什么?是因为我正在使用装饰器吗?
python ×3
dataframe ×1
dictionary ×1
docstring ×1
facebook ×1
json ×1
methods ×1
pandas ×1
python-3.x ×1
return-type ×1