- Check whether a variable is defined or not in Python
- Defining a Variable :
- Check if a variable is defined or not in Python :
- 2 responses to “Check whether a variable is defined or not in Python”
- Python Cookbook by
- Testing if a Variable Is Defined
- Problem
- Solution
- Discussion
- Check if a variable is defined in Python
- 1. Using locals() function
- 2. Using vars() function
- 3. Using dir() function
- 4. Using globals() function
- Python: Determine whether variable is defined or not
- Visualize Python code execution:
- Python: Tips of the Day
Check whether a variable is defined or not in Python
The topic deals with the Python variables. Here we are going to determine if a Python variable exists or not.
Certainly, a variable is a container of data. In other words, we can store our data in a variable that we can use for our task.
Defining a Variable :
Data or information needs to be stored for future operations. Moreover, Variable gives the facility to store data.
Let’s see how we define a variable in Python.
a = 4 # a is the variable which stores some data b = 12.9 c = "Hello" # Defining a variable print (a,b,c) # printing the values of the variable
Now let’s continue to our topic without wasting any more time…
Check if a variable is defined or not in Python :
A very simple method to check,
Certainly, this is the topic to be dealt with. So let’s see below:
- First of all, if a variable is defined, it would have some data in it.
- If it is not defined then no data is there in it.
The following example will clear the concept regarding this,
a = 4 # a is the variable which stores some data b = 12.9 c = "Hello" # Defining a variable print (c) # c is defined so no error is raised print (d) # d is not defined so error is raised
Output : Hello Traceback (most recent call last): File "main.py", line 10, in print (d) NameError: name 'd' is not defined
So we can see, that there will be an error appear if our variable is not defined.
We can check the existence of a variable using the Python try and except can be used to deal with the following conditions.
- The code is written in the try block.
- If any kind of error arises, then statements in except block get executed.
- If there is no error, except block statements, they are not executed.
The following example may clarify the doubts regarding the use of try/except if any,
a = 10 # a is defined try: print (c) # variable c is not defined. # therefore error raises and control shifts to except block. except: print ("Variable is not defined")
Output : Variable is not defined
This is the way to determine or check whether a variable is defined or not in Python.
2 responses to “Check whether a variable is defined or not in Python”
a “try: .. except: ” block is pretty expensiv for just checking if a variable is defined, specially if it is checked like this in a loop. normally you can check it with:
“`python
if ‘c’ in dir():
print (c)
else:
print (“Variable is not defined”)
“`
to check if a variable is in a class dir() or dir().
It’s title is not about how to define variable. Just how to check if already defined. Few strings enough instead of article. As a result: TL;DR;
Python Cookbook by
Get full access to Python Cookbook and 60K+ other titles, with a free 10-day trial of O’Reilly.
There are also live events, courses curated by job role, and more.
Testing if a Variable Is Defined
Problem
You want to take different courses of action based on whether a variable is defined.
Solution
In Python, all variables are expected to be defined before use. The None object is a value you often assign to signify that you have no real value for a variable, as in:
try: x except NameError: x = None
Then it’s easy to test whether a variable is bound to None :
if x is None: some_fallback_operation( ) else: some_operation(x)
Discussion
Python doesn’t have a specific function to test whether a variable is defined, since all variables are expected to have been defined before use, even if initially assigned the None object. Attempting to access a variable that hasn’t previously been defined raises a NameError exception (which you can handle with a try / except statement, as you can for any other Python exception).
It is considered unusual in Python not to know whether a variable has already been defined. But if you are nevertheless in this situation, you can make sure that a given variable is in fact defined (as None , if nothing else) by attempting to access it inside a try clause and assigning it the None object if the access raises a NameError exception. Note that None is really nothing magical, just a built-in object used by convention (and returned by functions that exit without returning anything specific). You can use any other value suitable for your purposes to initialize undefined variables; for a powerful and interesting example, see Recipe 5.24.
Instead of ensuring that a variable is initialized, you may prefer to test whether it’s defined where you want to use it:
try: x except NameError: some_fallback_operation( ) else: some_operation(x)
This is a perfectly acceptable alternative to the code in the recipe, and some would say it’s more Pythonic. Note, however, that if you choose this alternative, you have to code things in this order: the anomalous, error case first, then the normal, no-error case. With the recipe’s approach, you may want to invert the guard condition to if x is not None and code the normal case first. These points are minutiae, to be sure, but sometimes clarity can be improved this way. Furthermore, you must be careful to avoid the variation in this alternative:
try: x some_operation(x) except NameError: some_fallback_operation( )
In this variation, the call to some_operation is also covered by the exception handler, so if there is a bug in the some_operation function, or in any function called from it, this code would mask the bug and apparently proceed to operate normally when it should fail with an error message. You should always be careful that your try clauses (in try / except statements) do not accidentally cover more code than you actually intend to cover, which might easily mask bugs. The else clause in the try / except statement is for code that should execute only if no exception was raised but should not itself be covered by the exception handler, because you do not expect exceptions from it and want to diagnose the problem immediately if exceptions do occur.
Many situations that you might think would naturally give rise to undefined variables, such as processing configuration files or web forms, are handled better by employing a dictionary and testing for the presence of a key (with the has_key method, a try / except , or the get or setdefault methods of dictionary objects). For example, instead of dealing with a user configuration file this way:
execfile('userconfig') try: background_color except NameError: background_color = 'black' try: foreground_color except NameError: foreground_color = 'white' .
config = dict(globals( )) execfile('userconfig', config) background_color = config.get('background_color', 'black') foreground_color = config.get('foreground_color', 'white') .
dict requires Python 2.2, but you can get a similar effect in earlier versions of Python by using config = globals().copy( ) instead. Using an explicitly specified dictionary for exec , eval , and execfile is advisable anyway, to keep your namespace under control. One of the many benefits of using such an explicitly specified dictionary is, as shown here, that you don’t need to worry about undefined variables but can simply use the dictionary’s get method to fetch each key with an explicitly specified default value to be used if the key is not present in the dictionary.
If you know for sure which namespace the variable is in (i.e., specifically locals or specifically globals ), you can also use methods such as has_key or get on the relevant dictionary. However, variables that are in neither locals nor globals may exist (thanks to the nested scopes feature that is optional in Python 2.1, but is always on in Python 2.2 and later). Also, the special namespace directories returned by locals and globals are not suitable for mutating methods such as setdefault , so you’re still better off arranging to use your own explicit dictionary rather than the local or global namespaces, whenever that’s feasible.
Check if a variable is defined in Python
This post will discuss how to check if a variable is defined in Python.
1. Using locals() function
To check if the variable is defined in a local scope, you can use the locals() function, which returns a dictionary representing the current local symbol table.
2. Using vars() function
Alternatively, you can use no-arg vars() function, which acts like locals() function.
3. Using dir() function
Without arguments, the dir() function returns the list of names in the current local scope.
4. Using globals() function
Finally, to check for the existence of a global variable, you can use the globals() function. It returns a dictionary representing the current global symbol table.
That’s all about determining whether a variable is defined in Python.
Average rating 5 /5. Vote count: 24
No votes so far! Be the first to rate this post.
We are sorry that this post was not useful for you!
Tell us how we can improve this post?
Thanks for reading.
Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and help us grow. Happy coding 🙂
This website uses cookies. By using this site, you agree to the use of cookies, our policies, copyright terms and other conditions. Read our Privacy Policy. Got it
Python: Determine whether variable is defined or not
Write a Python program to determine if a variable is defined or not.
Sample Solution:
Python Code:
try: x = 1 except NameError: print("Variable is not defined. ") else: print("Variable is defined.") try: y except NameError: print("Variable is not defined. ") else: print("Variable is defined.")
Variable is defined. Variable is not defined.
Visualize Python code execution:
The following tool visualize what the computer is doing step-by-step as it executes the said program:
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource’s quiz.
Follow us on Facebook and Twitter for latest update.
Python: Tips of the Day
Converting string into datetime:
datetime.strptime is the main routine for parsing strings into datetimes. It can handle all sorts of formats, with the format determined by a format string you give it:
from datetime import datetime datetime_object = datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')
The resulting datetime object is timezone-naive.
- Python documentation for strptime: Python 2, Python 3
- Python documentation for strptime/strftime format strings: Python 2, Python 3
- strftime.org is also a really nice reference for strftime
- strptime = «string parse time»
- strftime = «string format time»
- Pronounce it out loud today & you won’t have to search for it again in 6 months.
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook