Tuesday, January 31, 2012

How to check if variable exists in Python.

This is a pretty common problem as Python does not offer any variable checking mechanism and when we try to use non defined variable it will throw an NameError exception.
We can do try/expect way but it is not very useful, instead I propose to declare a Perl-style function.

def defined(var):
    return var in globals()


if defined('temp'):
    print('defined')
else:
    print('undef!')


We have to quote a variable but that shouldn't be a problem. This isn't very stylish or probably the best way to do it, but it works like a charm.

No comments: