Python: NameError: free variable 're' referenced before assignment in the scope

I have a weird NameError in Python 3.3.1 (win7).

Code:

import re # ... # Parse exclude patterns. excluded_regexps = set(re.compile(regexp) for regexp in options.exclude_pattern) # This is line 561: excluded_regexps |= set(re.compile(regexp, re.I) for regexp in options.exclude_pattern_ci) 

Error:

 Traceback (most recent call last): File "py3createtorrent.py", line 794, in <module> sys.exit(main(sys.argv)) File "py3createtorrent.py", line 561, in main excluded_regexps |= set(re.compile(regexp, re.I) for regexp in options.exclude_pattern_ci) File "py3createtorrent.py", line 561, in <genexpr> excluded_regexps |= set(re.compile(regexp, re.I) for regexp in options.exclude_pattern_ci) NameError: free variable 're' referenced before assignment in enclosing scope 

Note that line 561, where the error occurs, is the second line in the code above. In other words: re not a free variable. This is just a regular expression module, and in the first line it can be perfectly edited.

It seems to me that the link to re.I is causing the problem, but I do not see how.

+9
source share
3 answers

Most likely you are assigning re (presumably unintentionally) at some point below line 561, but in the same function. This reproduces your error:

 import re def main(): term = re.compile("foo") re = 0 main() 
+8
source

the "free variable" in the trace suggests that it is a local variable in the enclosing area. something like that:

  baz = 5 def foo(): def bar(): return baz + 1 if False: baz = 4 return bar() 

so baz refers to a local variable (one who has a value of 4), and not (presumably also existing) global. To fix this, force baz globally:

  def foo(): def bar(): global baz return baz + 1 

so that he does not try to resolve the name for the non-local version of baz. Better yet, find where you use re in a way that looks like a local variable (generator expressions / lists are a good place to check) and call it something else.

+7
source

Other explanations are perfect, but let me add another option that I just discovered. Because Python 3 prefers iterators over “physical” lists, you need to be more careful:

 def foo(): re = 3 faulty = filter(lambda x: x%re, range(30)) del re return faulty list(foo()) 

The filter expression is evaluated only after the return statement in the last line, in particular after del re . Therefore, the last line explodes with an error:

 NameError: free variable 're' referenced before assignment in enclosing scope 
0
source

Source: https://habr.com/ru/post/944983/


All Articles