From: catalinfest on
Hi everyone .
My questions is "why vars().has_key('b') is False ?'
I expecting to see "True" because is a variable ...
Thanks
Please see code bellow .
>>> x=11
>>> def something():
.... b=25
....
>>> vars().has_key('x')
True
>>> vars().has_key('b')
False
>>> globals().has_key('x')
True
>>> globals().has_key('b')
False
>>>
From: Chris Rebert on
On Sun, Apr 4, 2010 at 1:42 AM, catalinfest(a)gmail.com
<catalinfest(a)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().

Cheers,
Chris
--
http://blog.rebertia.com
From: Paul McGuire on
On Apr 4, 3:42 am, "catalinf...(a)gmail.com" <catalinf...(a)gmail.com>
wrote:
> Hi everyone .
> My questions is "why vars().has_key('b') is False ?'
> I expecting to see "True" because is a variable ...
> Thanks

Yes, 'b' is a var, but only within the scope of something(). See how
this is different:

>>> def sth():
.... b = 25
.... print 'b' in vars()
....
>>> sth()
True

(Also, has_key() is the old-style way to test for key existence in a
dict, and is kept around for compatibility with old code, but the
preferred method now is to use 'in'.)

-- Paul
From: Chris Rebert on
> 2010/4/4 Chris Rebert <clp2(a)rebertia.com>
>>
>> On Sun, Apr 4, 2010 at 1:42 AM, catalinfest(a)gmail.com
>> <catalinfest(a)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(a)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
From: Chris Rebert on
Ah, (bleep). Disregard both my responses.
Darn headache.

Cheers,
Chris
--
Definitely going to bed now.
http://blog.rebertia.com