Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the pythonic way of conditional variable initialization?

Tags:

python

Due to the scoping rules of Python, all variables once initialized within a scope are available thereafter. Since conditionals do not introduce new scope, constructs in other languages (such as initializing a variable before that condition) aren't necessarily needed. For example, we might have:

def foo(optionalvar = None):
    # some processing, resulting in...
    message = get_message()
    if optionalvar is not None:
        # some other processing, resulting in...
        message = get_other_message()
    # ... rest of function that uses message

or, we could have instead:

def foo(optionalvar = None):
    if optionalvar is None:
        # processing, resulting in...
        message = get_message()
    else:
        # other processing, resulting in...
        message = get_other_message()
    # ... rest of function that uses message

Of course, the get_message and get_other_message functions might be many lines of code and are basically irrelevant (you can assume that the state of the program after each path is the same); the goal here is making message ready for use beyond this section of the function.

I've seen the latter construct used several times in other questions, such as:

  • https://stackoverflow.com/a/6402327/18097
  • https://stackoverflow.com/a/7382688/18097

Which construct would be more acceptable?

like image 414
Robert P Avatar asked Dec 06 '11 18:12

Robert P


People also ask

What is initialization of variable?

Initializing a variable means specifying an initial value to assign to it (i.e., before it is used at all). Notice that a variable that is not initialized does not have a defined value, hence it cannot be used until it is assigned such a value.

In which method should all variables be initialized in Python?

If the value is not arbitrary and simply a default value that can be changed you should be using a default value in the __init__ method that can be overridden. It can also actually be a valid initial state, which is also not arbitrary and you should set it in the __init__ method.

What is conditional variable?

Condition variables are synchronization primitives that enable threads to wait until a particular condition occurs. Condition variables are user-mode objects that cannot be shared across processes. Condition variables enable threads to atomically release a lock and enter the sleeping state.


1 Answers

Python also has a very useful if syntax pattern which you can use here

  message = get_other_message() if optional_var else get_message()

Or if you want to compare strictly with None

  message = get_other_message() if optional_var is not None else get_message()

Unlike with example 1) you posted this doesn't call get_message() unnecessarily.

like image 134
Mikko Ohtamaa Avatar answered Sep 27 '22 20:09

Mikko Ohtamaa