Problem
I have a code like this
if condition:
a = f(x)
else:
a = g(y)
Initialization of a
inside of the block looks bad for me. Can it be written better?
I cannot use ternary operator, because names of functions and/or lists of arguments are long. Saying "long" I mean that the following expression
a = f(x) if condition else g(y)
will take more than 79 (sometimes even more than 119) symbols with real names instead of a
, f
, g
, x
, y
and condition
.
Usage of multiple slashes will make the code ugly and messy.
I don't want to initialize a
with result of one of the functions by defaul, because both function are slow and I cannot allow such overhead
a = g(y)
if condition:
a = f(x)
I can initialize the variable with None
, but is this solution pretty enough?
a = None
if condition:
a = f(x)
else:
a = g(y)
Let me explain my position: in C and C++ variables inside of a block have the block as their scope. In ES6 the let
keyword was introduced — it allows to create variables with the same scoping rules as variables in C and C++. Variables defined with old var
keyword have similar scoping rules as in Python.
That's why I think that initialization of variables should be made outside blocks if I want to use the variables outside these blocks.
Update
Here is more complicated example
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)
I go through elements of some generator gen
, process them and perform some actions on the result
on each iteration.
Then I want to do something with the last result
outside of the loop.
Is it pythonic enough to not assign a dummy value to the result
beforehand?
Doesn't this make the code less readable?
Question
Is it good to initialize variables inside if
/else
/for
/etc. in Python?