python - How to access var within function but outside subfunction -
i have following function, includes 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) url in tv_urls not in previously_parsed_tv_urls] previously_parsed_tv_urls = tv_urls.union(api_urls) function()
however, don't have access previously_parsed_tv_urls
. how access within _get_all_related
function?
here error get:
unboundlocalerror: local variable 'previously_parsed_tv_urls' referenced before assignment
if want reference earlier defined name, in "higher" scope, python fine it. grants sorts of power, when you're messing around in interpreter.
however, python pretty generous @ trying stop doing things can bite or cause nasty, difficult debug problems. unboundlocalerror
comes in.
as redefine name in particular scope, python marks local scope (only), , not higher provide value. keeps accidentally mucking higher scopes without explicitly requesting it.
as andrea corbellini mentioned, python 3 adds nonlocal keyword permit make such explicit request. pep 3104 pretty exhaustively describes change in scoping rules permits, comparing both python without nonlocal
other common languages of kind.
Comments
Post a Comment