Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute function only if a variable is True

I would like to run a function only if a statement is True. For example, i have:

def foo():
    # do something

And i want to run this only when

var == True

And in key handler I don't want to do something like this:

if k.key() == Key_UP and var:
    foo()

I call this function from multiple places and I don't want to repeat var condition. Also, I don't want something like this:

def foo():
    if var:
        # do something

The last one I showed is the nearest to my needs, but still i think it can be done some other way. Idiomatic for Python 3.

Greetings!

PS. I want to get something like this:

def foo() if var == True:
    # do something
like image 599
Marek Avatar asked Dec 24 '22 21:12

Marek


1 Answers

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
like image 130
Alexander Avatar answered Dec 27 '22 11:12

Alexander