访问嵌套函数中的顶级函数参数

时间:2015-09-19 06:36:41

标签: python function

我的generate_report函数有2个参数。在generate_report函数中,我有另一个名为generate_sub_report的函数。我想在report_type中使用参数date_rangegenerate_sub_report

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 = ...

如何在report_type中使用功能参数date_rangegenerate_sub_report?我想说的是,如何让generate_sub_report继承generate_report的参数?

已编辑/已更新的问题

运行以下代码。

它抛出: UnboundLocalError: local variable 'date_range' referenced before assignment

如果我改变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')

我的第一个问题仍然存在:如何在较大函数内的嵌套/内部函数中使用顶级函数的参数?这可能是超级基本的,我可能是一个白痴,大拇指向下,这没关系。我显然不理解一些非常基本的东西。抱歉最初缺乏清晰度。

1 个答案:

答案 0 :(得分:3)

report_type已经可以使用generate_subreport,因为它会被自动捕获。这是证据:

>>> 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
>>>

更新

恭喜,您已经发现了一个已知的Python疣。 任何分配的变量都假定为局部变量

这有效:

>>> def generate_report(date_range):
...   def get_keyword_report_request():
...     print date_range
...   get_keyword_report_request()
...
>>> generate_report('Annually')
Annually

但这失败了

>> 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看到你在内部函数中分配了date_range变量,并决定它需要在内部函数中声明一个新的date_range局部变量,并且当你调用{{1}时它会引发错误,因为内部print date_range尚未初始化。

您的修复 - 是删除date_range作业。它什么都没做。

date_range = date_range