Python's not that close to English
-
I've just substituted fifty-ish instances of this pattern.
if params["required_param"] is u"" or None: # Complain about user error else: # Assume params["required_param"] is a non-empty string
I've also found this pattern twice:
if string_or_none is not (u"" or None): # Assume string_or_none is a non-empty string
Fortunately, we've never had a value of
None
reach the first test oru""
reach the second.Notes for those not acquainted to Python:
- <nobr>"
is not
"</nobr> is its own operator, such that <nobr>"x is not y
"</nobr> means <nobr>"not (x is y)
"</nobr> rather than <nobr>"x is (not y)
"</nobr>; - "
or
" has lower precedence than <nobr>"is not
"</nobr> - "
x or y
" evaluates toy
ifx
is falsy.
- <nobr>"
-
-
import clr; import System; if System.String.IsNullOrEmpty(params["required_param"]): # Suggest user inadvertence else: # Assume params["required_param"] is a non-empty string
-
```
if string_or_none not in [u"", None]:FTFY</blockquote> I went with a simple: if string_or_none: Also, @discoursebot.
-
@Zecc - Days Since Last Discourse Bug: -1
-
ok, yes that would work, but it would also catch the case where string_or_null is the number 0, or the boolean value False, or even any class instance that
bool(string_or_null)
returnsFalse
for.not sure if that is desired or not, but my change preserves original intent.
:-P
-
And if you're that interested, the first
if
I rewrote as:if not params.get("required_param"):
get()
returns the value in the dictionary if the key is present or a default if it's not, where the default default isNone
if no default is given.
-
ok, yes that would work, but it would also catch the case where string_or_null is the number 0, or the boolean value False, or even any class instance that bool(string_or_null) returns False for.
That's true.not sure if that is desired or not, but my change preserves original intent.
-
You've made me check.
>>> "" is u"" False >>> "" == u"" True >>> "" in [u""] True
-
It just occurred to me that these strings aren't being trimmed or checked for something other than whitespace.
sigh
-
get() returns the value in the dictionary if the key is present or a default if it's not
I dunno python, but there's a common error here in JS land if the value itself is falsey...
-
Of course, if you were using this string for something like opening a file, the pythonest way would be:
try: #stuff except ValueError: #complain to user