Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use the "as" mechanism in an if statement

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?

like image 328
Farhadix Avatar asked Nov 17 '13 20:11

Farhadix


3 Answers

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/

like image 125
Maxime Lorant Avatar answered Oct 13 '22 01:10

Maxime Lorant


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])
like image 1
jwodder Avatar answered Oct 13 '22 01:10

jwodder


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__()
...
like image 1
alexis Avatar answered Oct 13 '22 01:10

alexis