Reputation: 2481
I saw the code snippet that I think it is illegal, but not sure yet.
This is not exactly the same code, but I try to keep the original as much as I can.
def validate_check(string):
try:
len(string) > 0
# do something
except Error:
# do something
Doesn't len(string) > 0
have to be in condition statement? Or is it something python syntax?
Upvotes: 0
Views: 59
Reputation: 199
If string is None
, the len
function will raise an error.
Perhaps it's the reason why your function is named validate_check
.
Upvotes: 1
Reputation: 30240
Doesn't
len(string) > 0
have to be in condition statement?
No, but the example you've provided doesn't make a ton of sense.
Here's a different, similar construction that might help:
x = input()
try:
10 / int(x)
except ZeroDivisionError:
print("Can't divide by zero")
except ValueError:
print("Can't convert to int")
The result of 10 / int(x)
is calculated (to see whether it will raise an error), but the result of that calculation is thrown away.
The reason I say your example is a bit weird is because the comparison with zero will have no effect whatsoever. So while the code will serve as a way of testing whether len
can be called on string
, that's about all it'll do.
Upvotes: 4
Reputation: 27323
This is valid syntax. But if you write:
len(string) > 0
print("hi")
then "hi" will be printed regardless of the length of the string. The only relevance this statement has is that it will throw an exception when either string
has no length, or the result of len(string)
is not comparable to 0.
What the author of the code is doing is avoiding the more complicated check if isinstance(string, str) and string:
(or, I guess, if isinstance(string, collections.abc.Sized) and len(string) > 0
).
Upvotes: 1