I know the title seems crazy, but it is true. Here is my predicament. First, I am still a beginner at Python so please be considerate. I am trying to test if a variable exists. Now the variable comes from a file that is parsed in yaml. Whenever I try this code,
if not name['foo']:
print "No name given."
return False
Python does as you would expect and returns false. However, when I try to change it to this code,
try:
name['foo']
except:
print "ERROR: No name given."
raise
the exception is never risen. I have searched and searched and could not find any questions or sites that could explain this to me. My only thought is that the parser is "tricking" the exception handler, but that doesn't really make sense to me.
I have made sure that there were no white spaces in the name field of the document I am parsing. The field has the format:
*name: foo
*ver: bar
Like I have said, I made sure that foo was completely deleted along with any whitespace between lines. If anyone could help, it would be greatly appreciated.
EDIT:
And I apologize for the negative logic in the if statement. The function has to go through a series of checks. The best way I could think of to make sure all the checks were executed was to return true at the very end and to return false if any individual check failed.
A few things:
That shouldn't throw an exception! You're doing name['foo']
in two places and expecting different behavior.
The name
doesn't behave like a dictionary, if it did you would NOT get a return of False
in the first example, you'd get an exception. Try doing this:
name = {} name['foo']
Then you'll get a KeyError
exception
Don't ever have an except:
block! Always catch the specific exception you're after, like IndexError
or whatever
I don't understand why you think it would raise an exception. The key evidently exists, otherwise the first snippet would not work. The value for that key is obviously some false-y value like False
, None
, []
or ''
.
Python does as you would expect and returns false.
The exception ( KeyError
) will be thrown only if there is no key in a dictionary (assuming name
is a dictionary). If you do
if not name['foo']:
and it does not throw an exception, then it means that "foo"
is in name
but the value evaluates to boolean false (it can be False
, None
, empty string ""
, empty list []
, empty dictionary {}
, some custom object, etc. etc.). Thus wrapping name['foo']
with try:except:
is pointless - the key is there.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.