Python: should initializing variables inside blocks be avoided?

Problem

I have code like this

if condition:
    a = f(x)
else:
    a = g(y)

Initialization ainside a block looks bad to me. Could it be better written?

I cannot use the ternary operator because function names and / or argument lists are long. When I say long, I mean the following expression

a = f(x) if condition else g(y)

will take more than 79 (sometimes even more 119) to the names of characters instead of a, f, g, x, yand condition. Using multiple slashes will make the code ugly and messy.

I do not want to initialize awith the result of one of the defaul functions, because both functions are slow, and I cannot allow such utility

a = g(y)
if condition:
    a = f(x)

None, ?

a = None
if condition:
    a = f(x)
else:
    a = g(y)

: C ++ . ES6 let — , C ++. , var , , Python. , , .

Update

for obj in gen:
    # do something with the `obj`
    if predicate(obj):
        try:
            result = f(obj)
        except Exception as e:
            log(e)
            continue
    else:
        result = g(obj)
    # do something useful with the `result`
else:
    result = h(obj)

display(result)

gen, result . - result .

pythonic, result? ?

if/else/for/ .. Python?

+4
3

, , python.

  • python / . a = f(x) , f a. a . . .

  • python , , . , / , . if-else . , , , if/else . . this. global nonlocal . python let, .

, a . , f g, , . if else , a - ( if else, ). , , try-except-else, , , a except / .

, , , if-else :

  • if, else, . try-except-else , .

  • , -, , a, res .. , .

+2

Python ... - ,

if <condition>:
    a = f()
else:
    a = g()

++, ++, ++, ++ Python... .

+5

, .

#this is not, strictly, needed, but it makes the 
#exception handler more robust
a = b = None

try:
    if condition:
        a = f(x)
        b = v(x)
    else:
        a = g(y)
        b = v2(x)

    return w(a, b)

except Exception, e:
    logger.exception("exception:%s" % (e))
    logger.exception("  the value of a was:%s" % (a))
    logger.exception("  the value of b was:%s" % (b))
    raise 

, - . , .

, , return w(a, b), a b NameError , .

, , -unittesting - URL-, . get/post , , , , , , , .

, , , , None. , a None, - logger("a.attr1:%s" % (getattr(a, "attr1","?")

+1

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


All Articles