About this question
I want to check if a variable exists. Now I'm doing something like this:
try:
yourVar
except NameError:
# Do something.
Are there other ways without exceptions?
I want to check if a variable exists. Now I'm doing something like this:
try:
yourVar
except NameError:
# Do something.
Are there other ways without exceptions?
Log in to share your answer and help other learners.
Log in to answerBest Answer · By JanBask Python Expert
Answered on Apr 7, 2021
To solve python check if a variable exists you should follow the below-method varies with the type of variable.
1. If you want to check the existence of a local variable use:
if 'yourVar' in locals():
# yourVar exists.2.if you want to check the existence of a global variable use:
if 'yourVar' in globals():
# yourVar exists.3.If you want to check if an object has an attribute:
if hasattr(obj, 'name_attr'):
# obj.name_attr exists.Hope my answer helps!
Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.
Most-read guides across JanBask
Common Python interview questions, answered
Guides, tips and career advice on Python from JanBask experts.
Python How to Become a Python Developer: A Step-by-Step Guide for Beginners
Discover how to become a Python Developer via a practical 7-step guide build projects, maintain clean code, practice daily, and…
Python PCEP Certification Guide: Entry-Level Python Programmer Certification
Explore this PCEP certification guide for insights on cost, exam format, passing score, application, training, and study tips.…
Python Top 50+ Python Projects ideas for Beginners to Advanced
Discover innovative Python project ideas, explore advanced Python projects, and find good Python projects for beginners and…
Python How To Comment Out Multiple Lines In Python Like A Pro
Commenting out code is a common practice among programmers. It allows you to temporarily disable parts of your code without…