pythonscrapypython-assignment-expression

Walrus Operator: NameError: free variable 'it' referenced before assignment in enclosing scope


I want to create a list using the walrus operator like this:

myvar = tr_list[8].css('td ::text').extract()
item['myvar'] = [
    it := re.sub(PATTERN, "", i).strip() 
    for i in myvar 
    if len(it) > 0
]

And I get this error:

it := re.sub(PATTERN, "", i).strip() for i in myvar if len(it) > 0
NameError: free variable 'it' referenced before assignment in enclosing scope

On the other hand it works when I do it this way:

myvar = tr_list[8].css('td ::text').extract()
item['myvar'] = [
    re.sub(PATTERN, "", i).strip() 
    for i in myvar 
    if len(re.sub(PATTERN, "", i).strip()) > 0
]

where:

PATTERN = "\r|\t|\n"

Can anyone help? I don't know what I am missing here


Solution

  • Ok. I think I finally solved it by changing it to:

    myvar = tr_list[8].css('td ::text').extract()
    item['myvar'] = [
        n for i in myvar
        if len(n := re.sub(PATTERN, "", i).strip()) > 0
    ]