The Python Oracle

Is there a clean way to check a variable inside a loop on the first iteration only or before its execution?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Track title: CC C Schuberts Piano Sonata No 13 D

--

Chapters
00:00 Is There A Clean Way To Check A Variable Inside A Loop On The First Iteration Only Or Before Its Exe
01:10 Accepted Answer Score 2
01:41 Answer 2 Score 1
02:30 Thank you

--

Full question
https://stackoverflow.com/questions/6498...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #algorithm #loops #ifstatement #whileloop

#avk47



ACCEPTED ANSWER

Score 2


I would begin with grouping the functions from the while loop into a new function. Then before the loop we check if visual is True, if it is then we decorate functions() with a wrapper.

def functions():
    function1()
    function2()

def _visual_decorator(func):
    def _wrapper(*args, **kwargs):
        print("Something meaningful")
        return func(*args, **kwargs)
    return _wrapper

if visual:
    functions = _visual_decorator(functions)

while True:
    functions()

Full working example




ANSWER 2

Score 1


You're after a branchless programming approach. You should transform your loop so that it doesn't use the first branching if.
To do that generally depends on the language you're using and the features that it provides.
For example, in Python, you could put two functions in a map and use one of them according to the variable value:

functions = {True: print, False: lambda x: x}
value = False
func = functions[value]
while True:
  func("Something useful")
  function1()
  function2()

This is one way to do it, and it is not the only way. Other languages have their own way to achieve the same thing.
Note that while in Python this might not give much difference, brancheless programming in general could potentially optimize your programs running time, sometimes by orders of magnitude!