[英]Accessing Top-level function parameters within a Nested Function
My generate_report
function has 2 parameters. 我的generate_report
函数有2个参数。 Within the generate_report
function I have another function named generate_sub_report
. 在generate_report
函数中,我还有另一个名为generate_sub_report
函数。 I want to use the parameters report_type
and date_range
within generate_sub_report
. 我想在generate_sub_report
使用参数report_type
和date_range
。
def generate_report(report_type, date_range):
with open('file.csv') as f:
# do some stuff
def generate_sub_report():
report_map = {'Budget': ['a', 'b', 'c'], 'Finance': ['d', 'e', 'f']}
get_list_from_dict = report_map.get(report_type)
if date_range == 'Summary':
columns = ...
How do I use the function parameters report_type
and date_range
within generate_sub_report
too? 如何在generate_sub_report
使用函数参数report_type
和date_range
? What I'm trying to say is, how can I make generate_sub_report
inherit the parameters from generate_report
? 我想说的是,我如何才能让generate_sub_report
继承参数generate_report
?
Edited/Updated Question 编辑/更新的问题
Run the code below. 运行下面的代码。
It throws: UnboundLocalError: local variable 'date_range' referenced before assignment
它抛出: UnboundLocalError: local variable 'date_range' referenced before assignment
If I change def get_keyword_report_request(report_type, date_range):
with the thought that maybe I have to pass the parameters through the nested function, it then throws: 如果我更改def get_keyword_report_request(report_type, date_range):
考虑到也许我必须通过嵌套函数传递参数,则它会抛出:
TypeError: get_keyword_report_request() missing 2 required positional arguments: 'report_type' and 'date_range'
def generate_report(report_type, date_range):
def get_keyword_report_request():
columns_map = {
"Account": ["AccountName", "AccountId", "Impressions", "Clicks", "Spend",
"Conversions"],
"Campaign": ["AccountName", "AccountId", "CampaignName", "Status", "Impressions",
"Clicks", "Spend", "Conversions"],
"Keyword": ["AccountName", "AccountId", "CampaignName", "CampaignStatus",
"AdGroupName", "AdGroupStatus", "Keyword", "KeywordStatus",
"BidMatchType", "CurrentMaxCpc", "Impressions", "Clicks", "Spend",
"AveragePosition", "Conversions"],
"Ad group": ["AccountName", "AccountId", "CampaignName", "AdGroupName", "Status",
"Impressions", "Clicks", "Spend", "AveragePosition", "Conversions"],
"Search Query": ["AccountName", "AccountId", "CampaignName", "CampaignStatus",
"AdGroupName", "SearchQuery", "Keyword", "BidMatchType",
"DeliveredMatchType", "Impressions", "Clicks", "Spend",
"AveragePosition", "Conversions"],
"Ad": ["AccountName", "AccountId", "CampaignName", "AdGroupName", "Status",
"AdTitle", "AdDescription", "DisplayUrl", "DestinationUrl", "AdStatus",
"Impressions", "Clicks", "Spend", "AveragePosition", "Conversions"]
}
columns = columns_map.get(report_type)
if isinstance(date_range, list):
# do this
print('wha')
elif isinstance(date_range, str):
date_range = date_range
print(date_range)
return(date_range, report_type)
get_keyword_report_request()
generate_report('Keyword', 'Summary')
My initial question still remains: How can I use the top-level function's parameters in a nested/inner function within the larger function? 我最初的问题仍然存在:如何在较大函数的嵌套/内部函数中使用顶级函数的参数? This is probably super-basic and I'm probably an idiot, thumbs down, that's fine. 这可能是非常基础的,我可能是个白痴,对此表示赞同。 I clearly don't comprehend something very fundamental. 我显然不了解非常基本的内容。 Sorry for the lack of clarity initially. 很抱歉最初缺乏清晰性。
The report_type
is already available to the generate_subreport
because it is automatically captured. report_type
已经可用于generate_subreport
因为它是自动捕获的。 Here's the proof: 这是证明:
>>> def generate_report(report_type):
... def generate_subreport():
... print "the report type is " + report_type
... generate_subreport()
...
>>> generate_report('Big Report')
the report type is Big Report
>>> generate_report('Small Report')
the report type is Small Report
>>>
Congratulations, you've hit one of the known Python warts. 恭喜,您遇到了一种已知的Python疣。 Any variables that are assigned are assumed to be a local variable . 假定所有分配的变量都是局部变量 。
This works: 这有效:
>>> def generate_report(date_range):
... def get_keyword_report_request():
... print date_range
... get_keyword_report_request()
...
>>> generate_report('Annually')
Annually
But this fails 但这失败了
>> def generate_report(date_range):
... def get_keyword_report_request():
... print date_range
... date_range = 'Monthly' # one extra line
... get_keyword_report_request()
...
>>> generate_report('Annually')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in generate_report
File "<stdin>", line 3, in get_keyword_report_request
UnboundLocalError: local variable 'date_range' referenced before assignment
Python saw that you're assigning to the date_range variable in the inner function, and decided that it needed to declare a new date_range
local variable in the inner function, and when you call print date_range
, it throws and error because the inner date_range
has not been initialised yet. Python看到您要在内部函数中分配给date_range变量,并决定需要在内部函数中声明一个新的date_range
局部变量,并且当您调用print date_range
,它会抛出错误,因为内部date_range
没有尚未初始化。
Your fix - is to remove the date_range = date_range
assignment. 您的解决方法-是删除date_range = date_range
分配。 It does absolutely nothing. 它绝对不做任何事情。
def generate_report(report_type, date_range):
def get_keyword_report_request():
columns_map = {'Account': ['AccountName', 'AccountId', 'Impressions', 'Clicks', 'Spend', 'Conversions'],
'Campaign': ['AccountName', 'AccountId', 'CampaignName', 'Status', 'Impressions', 'Clicks', 'Spend', 'Conversions'],
'Ad group': ['AccountName', 'AccountId', 'CampaignName', 'AdGroupName', 'Status', 'Impressions', 'Clicks', 'Spend', 'AveragePosition', 'Conversions'], #Adgroup status?
'Ad': ['AccountName', 'AccountId', 'CampaignName', 'AdGroupName', 'Status', 'AdTitle', 'AdDescription', 'DisplayUrl', 'DestinationUrl', 'AdStatus', 'Impressions', 'Clicks', 'Spend', 'AveragePosition', 'Conversions'],
'Keyword': ['AccountName', 'AccountId', 'CampaignName', 'CampaignStatus', 'AdGroupName', 'AdGroupStatus', 'Keyword', 'KeywordStatus', 'BidMatchType', 'CurrentMaxCpc', 'Impressions', 'Clicks', 'Spend', 'AveragePosition', 'Conversions'],
'Search Query': ['AccountName', 'AccountId', 'CampaignName', 'CampaignStatus', 'AdGroupName', 'SearchQuery', 'Keyword', 'BidMatchType', 'DeliveredMatchType', 'Impressions', 'Clicks', 'Spend', 'AveragePosition', 'Conversions']
}
columns = columns_map.get(report_type)
if isinstance(date_range, list):
# do this
print('wha')
elif isinstance(date_range, str):
# Commented out: date_range = date_range
print(date_range)
return(date_range, report_type)
get_keyword_report_request()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.