To check the existence of a local variable:
if 'myVar' in locals():
# myVar exists.
To check the existence of a global variable:
if 'myVar' in globals():
# myVar exists.
To check if an object has an attribute:
if hasattr(obj, 'attr_name'):
# obj.attr_name exists.
More Related Contents:
- Importing installed package from script raises “AttributeError: module has no attribute” or “ImportError: cannot import name”
- How do you create different variable names while in a loop? [duplicate]
- Simpler way to create dictionary of separate variables?
- django MultiValueDictKeyError error, how do I deal with it
- What’s the scope of a variable initialized in an if statement?
- How do I count occurrence of unique values inside a list
- What’s the best way to return multiple values from a function? [duplicate]
- Underscore _ as variable name in Python [duplicate]
- How to retry after exception?
- Elegant way to check if a nested key exists in a dict?
- SyntaxError inconsistency in Python?
- How to call function that takes an argument in a Django template?
- Python Django Global Variables
- How to get exception message in Python properly
- Python – Why is this class variable not defined in the method?
- How can I make silent exceptions louder in tkinter?
- Access to value of variable with dynamic name
- How to increment variable names/Is this a bad idea [duplicate]
- How do I put a variable’s value inside a string (interpolate it into the string)?
- Python: function and variable with the same name
- hasattr() vs try-except block to deal with non-existent attributes
- Should I use instance or class attributes if there will only be one instance? [closed]
- How to re-raise an exception in nested try/except blocks?
- How to pass a Bash variable to Python?
- How to retain leading zeros of int variables?
- How to return a custom 404 Not Found page using FastAPI?
- Re-raise exception with a different type and message, preserving existing information
- Catching exception in context manager __enter__()
- using variable in import command
- Multiple try codes in one block