Is it possible to use as
in if
statement like with
that we use, for example:
with open("/tmp/foo", "r") as ofile:
# do_something_with_ofile
This is my code:
def my_list(rtrn_lst=True):
if rtrn_lst:
return [12, 14, 15]
return []
if my_list():
print(my_list()[2] * mylist()[0] / mylist()[1])
Can I use if
in this type:
if my_list() as lst:
print(lst[2] * lst[0] / lst[1])
In first if
I called my_list
four times. I can use a variable but I want to know is there any way to use as
?
No. The if
statement is defined as:
if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
... where test
is a suite of test expression combined with or/and.
For more information, see: http://docs.python.org/3.3/reference/grammar.html
You can defined your variable before and then test its value:
lst = my_list()
if lst:
print(lst[2] * lst[0] / lst[1])
If you want some challenge (and for expiremental stuff only), you can change the Python grammar, have fun: http://www.python.org/dev/peps/pep-0306/
No. The Python grammar does not allow using "as
" outside of with
, except
, or import
constructs. You should instead do:
lst = my_list()
if lst:
print(lst[2] * lst[0] / lst[1])
You need to use a variable. with
supports the as
-variable because the object assigned to it is not the result of evaluating the with
-expression. (It is the value returned by that result's __enter__
method, see http://docs.python.org/release/2.5/whatsnew/pep-352.html. With (most) other statements, it's easy enough to catch the expression in a variable. I.e., with expr as v
is (partly) equivalent to:
_context = expr
v = _context.__enter__()
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With