In Python, how do I check if a variable exists?


This question already has an answer here:


Why do you need to know? If the code breaks because of this, it's probably because the code is wrong anyway and needs to be fixed.

That said, try checking if 'x' in locals() or if 'x' in globals(), as appropriate to where you're expecting it to be.

As they say in Python, "it's better to ask forgiveness than permission". So, just try and access the variable, and catch the error if it doesn't exist.

    print "x exists"
except UnboundLocalError:
    print "x doesn't exist"

However, I would really like to know why you think you need to do this. Usually, you would always set the variable before checking its value.

Need Your Help

Two entity managers in Spring

spring hibernate entitymanager transactionmanager

I had done this programmatically at some point - that is creating two entity managers with different data sources and providing them for different services.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.