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

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


> 2010/4/4 Chris Rebert <clp2 at rebertia.com>
>>
>> On Sun, Apr 4, 2010 at 1:42 AM, catalinfest at gmail.com
>> <catalinfest at gmail.com> 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 gmail.com> 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"
try:
    eval(var_name)
except NameError:
    defined = False
else:
    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?

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list