简体   繁体   English

如何在函数内但在子函数外访问var

[英]How to access var within function but outside subfunction

I have the following function, which includes a function inside it:我有以下函数,其中包含一个函数:

def function():
    previously_parsed_tv_urls = set()

    def _get_all_related(tv_urls):

        api_urls = [self._build_api_url_from_store_url(url)
                    for url in tv_urls not in previously_parsed_tv_urls]
        previously_parsed_tv_urls = tv_urls.union(api_urls)


    function()

However, I don't have access to previously_parsed_tv_urls .但是,我无权访问previously_parsed_tv_urls How would I access that from within the _get_all_related function?我将如何从_get_all_related函数中访问它?

Here is the error I currently get:这是我目前得到的错误:

UnboundLocalError: local variable 'previously_parsed_tv_urls' referenced before assignment

If you want to reference an earlier defined name, even in a "higher" scope, Python is generally fine with it.如果您想引用较早定义的名称,即使在“更高”的范围内,Python 通常也可以使用它。 This grants you all sorts of power, especially when you're just messing around in an interpreter.这赋予您各种权力,尤其是当您只是在解释器中胡闹时。

However , Python is also pretty generous at trying to stop you from doing things that can bite you or cause nasty, difficult to debug problems.然而,Python 也非常慷慨地试图阻止你做一些可能会咬你或导致讨厌的、难以调试的问题的事情。 This is where UnboundLocalError comes in.这就是UnboundLocalError用武之地。

As soon as you redefine a name in a particular scope, Python marks it as local to that scope (only), and will not look higher to provide a value.一旦您在特定范围内重新定义名称,Python 会将其标记为该范围的本地(仅),并且不会看起来更高以提供值。 This keeps you from accidentally mucking up higher scopes without explicitly requesting it.这可以防止您在没有明确请求的情况下意外破坏更高的范围。

As Andrea Corbellini mentioned, Python 3 adds the nonlocal keyword to permit you to make just such an explicit request.正如 Andrea Corbellini 所提到的,Python 3 添加了nonlocal 关键字以允许您发出这样一个明确的请求。 PEP 3104 pretty exhaustively describes the change in scoping rules this permits, comparing both to Python without nonlocal as well as other common languages of its kind. PEP 3104非常详尽地描述了这允许的范围规则的变化,将其与没有nonlocal语言的 Python 以及其他同类语言进行比较。

You're assigning to previously_parsed_tv_urls inside the inner function.您在内部函数中分配给previously_parsed_tv_urls When you do that, Python always makes it a local name throughout the function;当你这样做时,Python 总是在整个函数中使它成为一个本地名称; so your earlier access of the value will fail with the error you see.因此,您之前对该值的访问将失败,并显示您看到的错误。

However in this case there doesn't seem to be any reason to reassign the name.但是,在这种情况下,似乎没有任何理由重新分配名称。 Instead, you can update the existing set:相反,您可以更新现有集:

all_urls = tv_urls.union(api_urls)
previously_parsed_tv_urls.update(all_urls)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM