Python: Preventing if stairs

Whenever I encode something that requires a lot of conventions, I end up doing this:

if foo:
  if bar:
    if foobar:
      if barfoo:
        if foobarfoo:
          if barfoobar:
            # And forever and ever and ever

I can’t write if foo and bar and foobar and ...because I check the elements of the list of values ​​( if foo[1] == 'bar') inside ifsomewhere down the line, and if the index of the list does not exist, I get an error.

Is there a shortcut for conditionally checking such things or an alternative method? Thank.

+3
source share
7 answers

I can’t write if foo and bar and foobar and ... because I call the list items inside if if somewhere down the line and if the list index does not exist, I get an error.

python, and . , .

foo = dict()

if 'bar' in foo and foo['bar']:
    doSomething()
+8

:

if not foo:
    return

if not foobar:
    return

..

+5

, - , try/except - ( ), .

+2

if all((foo, bar, foobar, barfoo, foobarfoo, barfoobar)):
    print "oh yeah"

+2

, , ( , ).

+1

, . , , . , if-statement , . .

:

if foo and bar and foobar:
    ...
    if barfoo and foobarfoo and barfoobar:
        ...

. , .

def handle_bar():
    if barfoo and foobarfoo and barfoobar:
        ...

if foo and bar and foobar:
    ...
    handle_bar()

, , -, .

, , . , , , . , .

0

3 - 5 ( ), , , . . , .

"" (, ), :

def all_true(*args):
    for test in args:
        if bool(test) is False: return False 

    return True    

foo=bar=foobar=barfoo=foobarfoo=barfoobar=1

if foo:
  if bar:
    if foobar:
      if barfoo:
        if foobarfoo:
          if barfoobar:
             print "True by Stairs!"

if all_true(foo,bar,foobar,barfoo,foobarfoo,barfoobar):
    print "True by function!"

t=(foo,bar,foobar,barfoo,foobarfoo,barfoobar)

if all_true(*t): print "The tuple is true!"

l=[foo,bar,foobar,barfoo,foobarfoo,barfoobar]

if all_true(*l): print "list is true!"

bar=0
# run the same tests...

all_true() .

0
source

Source: https://habr.com/ru/post/1791615/


All Articles