The Python Oracle

Execute function only if a variable is True

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

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 2 Looping

--

Chapters
00:00 Execute Function Only If A Variable Is True
00:51 Accepted Answer Score 8
01:10 Answer 2 Score 2
01:31 Answer 3 Score 0
01:55 Thank you

--

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

--

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

--

Tags
#python #methods #idioms

#avk47



ACCEPTED ANSWER

Score 8


Like this?

 def foo():
    print('foo')

>>> bool = True
>>> if bool: foo()
foo

>>> bool = False
>>> if bool: foo()

If the above isn't suitable, I don't think it's clear what you'd like to do or why something like this wouldn't work:

def foo():
    if not var:
        return



ANSWER 2

Score 2


Depending on where and how var is declared, you may be able to write a decorator, which will allow you to have a syntax like that:

@if_true(var)
def foo():
     # body of the function

However, this isn't by any means more idiomatic than a simple if check in the body of the function, which you (for some reason) don't want.




ANSWER 3

Score 0


You could use the short circuit behavior of a boolean operation to accomplish the task but it is not clear that is what you are after.

# bit of setup
class K:
    def __init__(self, key):
        self._key = key
    def key(self):
        return self._key
def foo():
    print('\tfoo running')
    return 'foo!'
var = [True, False]
k = K(True)
m = K(False)

for thing in (k, m):
    for b in var:
        print('thing.key():{} - var:{}'.format(thing.key(), b))
        if thing.key():
            result = b and foo()
            print('\t', result)
>>> 
thing.key():True - var:True
    foo running
     foo!
thing.key():True - var:False
     False
thing.key():False - var:True
thing.key():False - var:False
>>>