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

C

catalinfest

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 ..... b=25
....
 
C

Chris Rebert

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
 
P

Paul McGuire

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:
.... b = 25
.... print 'b' in vars()
....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
 
C

Chris Rebert

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top