vars().has_key() question about how working .

Chris Rebert clp2 at
Sun Apr 4 05:16:14 EDT 2010

> 2010/4/4 Chris Rebert <clp2 at>
>> On Sun, Apr 4, 2010 at 1:42 AM, catalinfest at
>> <catalinfest at> wrote:
>> > Hi everyone .
>> > My questions is "why vars().has_key('b') is False ?'
>> > I expecting to see "True" because is a variable ...
>> The built-in constants and functions aren't global variables, they're
>> in the special __builtins__ dictionary/namespace, and thus not part of
>> globals() or vars().

On Sun, Apr 4, 2010 at 2:02 AM, Cata <catalinfest at> wrote:
> So is not possible to testing if a variable is defined with this functions
> vars(), globals(), locals() ?

No, you just need to add another case for __builtins__

The scopes Python consults when looking up a name are:
1. Local scope - locals()
2. Nested function scope(s) - [I don't think these vars can be listed
at runtime]
3. Global scope - globals()
4. Built-ins - __builtins__

If you want to just check whether a variable is currently
defined+accessible, a try-except is much simpler:
var_name = "foo"
except NameError:
    defined = False
    defined = True

However, wanting to test whether a variable is defined or not is
usually a sign of bad code.
Could you explain exactly why you want/need to do such testing?


More information about the Python-list mailing list