Search code examples
pythonenvironment-variablesspyderpyflakesundefined-variable

Python / Spyder - Undefined variable error, when variable is defined and shown in the environment. Code works even with the error


I am getting a strange error when defining variables in Python 4.1.5 (IDE:Spyder). However, even with the error, the code runs without any issues!

enter image description here

enter image description here

As you can see, the variable social_cost_of_carbon is stored as a variable, but I keep getting that error as show in picture 1 (the error writes: Undefined name 'social_cost_of_carbon' (Pyflakes E)

I feel that the way that i declare those variables might be the reason:

def convert_to_var(df):
    desc = []
    val = []  
    
    for i,row in df.iterrows():
        desc.append(i)
        val.append(row) 
        
    return dict(val)

val_dict = convert_to_var(IA)
locals().update(val_dict)

Since the code runs without any problems, I am not doing anything to resolve this. Do I need to worry and fix this, or do I just let it be and continue without dealing with the error since the code runs smoothly?

Thanking you in advance.


Solution

  • (Spyder maintainer here) As you guessed, the problem is that you're creating your variable dynamically with this line in your code:

    locals().update(val_dict)
    

    Since our linter can't find where that variable is properly declared, it reports that it's undefined. But it's safe for you to ignore that message.

    Note: Since Spyder 5.1.0, you can avoid the linter error by adding a comment at the end of the problematic line of the form # noqa.