A method by which Python determines whether a variable has been defined

  • 2020-04-02 13:54:14
  • OfStack

Determining whether a variable has been defined is a very important function of Python, and this article will briefly describe how to implement it.

There are many ways in Python to tell if a variable is already defined. Here are two of the most commonly used examples, as shown below:

Method 1: try except method:


def isset(v): 
   try : 
     type (eval(v)) 
   except : 
     return  0  
   else : 
     return  1  

Usage:


if isset('user_name'): 
  print 'user_name is defined' 
else 
  print 'user_name is not defined' 

Method 2: using namespaces:


'varname' in locals().keys()
'varname' in  dir()

The examples in this article are for reference only, and you can continue to summarize other approaches in your Python programming practice.


Related articles: