Python if not isset

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.

Читайте также:  Php запретить кэширование файла

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.

Источник

How to check if a Python variable exists?

There are two types of variable first one is local variable that is defined inside the function and the second one are global variable that is defined outside the function. Both are «lazy» in that they use Python iteration to pull values one at a time.

How to check if a Python variable exists?

Variables in Python can be defined locally or globally. There are two types of variable first one is local variable that is defined inside the function and the second one are global variable that is defined outside the function.

Читайте также:  Метод адамса мултона python

To check the existence of variable locally we are going to use locals() function to get the dictionary of current local symbol table.

Example:
Examples: Checking local variable existence

To check the existence of variable globally we are going to use globals() function to get the dictionary of current global symbol table.

Examples: Checking global variable existence

Python — How do I check if a variable exists?, The use of variables that have yet to been defined or set (implicitly or explicitly) is often a bad thing in any language, since it tends to indicate that the logic of the program hasn’t been thought through properly, and is likely to result in unpredictable behaviour.. If you need to do it in Python, the following trick, which is similar to yours, will ensure that a variable has some value Code sampleif hasattr(obj, ‘attr_name’):# obj.attr_name exists.Feedback

How do I check if a Python variable exists?

We use the following code to check if a variable exists in python.

Example

x =10 class foo: g = 'rt' def bar(self): m=6 print (locals()) if 'm' in locals(): print ('m is local variable') else: print ('m is not a local variable') f = foo() f.bar() print (globals()) if hasattr(f, 'g'): print ('g is an attribute') else: print ("g is not an attribute") if 'x' in globals(): print ('x is a global variable')

Output

We get the following output

, 'm': 6> m is local variable , '__builtins__': , '__file__': 'C:/Users/TutorialsPoint1/~.py', '__package__': None, 'x': 10, '__name__': '__main__', 'foo': , '__doc__': None> g is an attribute x is a global variable Process finished with exit code 0

How to check if a Python variable exists?, Variables in Python can be defined locally or globally. There are two types of variable first one is local variable that is defined inside the function and …

Check if a variable exists

I am using following method isset(var) to determine if a variable exists.

def isset(variable): try: variable except NameError: return False else: return True 

It returns True if variable exists. But if a variable doesn’t exist I get following:

Traceback (most recent call last): File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/usr/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/home/lenovo/pyth/master/vzero/__main__.py", line 26, in ss.run() File "vzero/ss.py", line 4, in run snap() File "vzero/ss.py", line 7, in snap core.display() File "vzero/core.py", line 77, in display stdout(session(username())) File "vzero/core.py", line 95, in session if isset(ghi): #current_sessions[user]): NameError: global name 'ghi' is not defined 

I don’t want all these errors. I just want it return False. No output. How can I do this?

Instead of writing a complex helper function isset and calling it

if not isset('variable_name'): # handle the situation 

in the place where you want to check the presence of the variable do:

try: # some code with the variable in question except NameError: # handle the situation 

In Python, how do I check if a variable exists?, Usually, you would always set the variable before checking its value. try: variable except NameError: print «It doesn’t Exist!» else: print «It exists!» You …

Читайте также:  Javascript append javascript file

«exists» keyword in Python?

I’ve recently made the following example for Pythons for . else:

def isPrime(element): """ just a helper function! don't get religious about it! """ if element == 2: return True elif element  

A fellow student told me, that this task can be done with Scala like this:

List(4, 4, 9, 12) exists isPrime 

Which gets lazy evaluated.

Does something similar like the exists-keyword exist in Python? Or is there a PEP for that?

myList = [4, 4, 9, 12] if not any(isPrime(x) for x in myList): print("The list did not contain a prime") 

Python also has all() which cranks through any sequence and returns True if all elements evaluate true.

any() and all() both have short-circuit evaluation: if any() finds any element that evaluates true, it stops and returns True ; and if all() finds any element that evaluates false, it stops and returns False .

Both are "lazy" in that they use Python iteration to pull values one at a time. For example:

import random def rand_sequence(n_max): while True: next_random = random.randint(0, n_max) print(next_random) yield next_random all(isPrime(x) for x in rand_sequence(20)) 

This will iterate until a non-prime number is found, then return False . It prints the numbers as a side-effect so you can watch it work. I just tried this and got:

P.S. I went to a talk at a Python conference, and the speaker mentioned that he commonly uses any() as a very efficient way to do a loop. A for loop re-binds the loop variable for each loop, but any() doesn't do that; it just keeps checking values. So if you use any() with a function that always returns None or a false value, it will iterate its way all to the end of the sequence, and according to that guy, it's the Fastest way in Python to do it. (And if your function returns a value that is not None and isn't false, you can use all() for the same trick. The only time it doesn't work is if sometimes the function returns a true value and sometimes it returns a false value. But you can force it to always work:

any(my_function(x) and False for x in sequence) 

P.P.S. Let's use all() to rewrite isPrime() ! I'll change the name to is_prime() to conform to PEP 8. http://www.python.org/dev/peps/pep-0008/

def is_prime(element): """ just a helper function! don't get religious about it! """ if element == 2: return True elif element  
[x for x in myList if isPrime(x)] 

How do I check if a Python variable exists?, How do I check if a Python variable exists? - We use the following code to check if a variable exists in python.Examplex =10 class foo: g = 'rt' def …

Источник

Оцените статью