Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python function that always return the same boolean value

In functional programming is sometimes useful to have a function that always return True (or False) for every parameter (or even multiple parameters).

Is there a built-in or a function defined in some module that have this exact behaviour?

like image 343
enrico.bacis Avatar asked Jan 20 '16 13:01

enrico.bacis


People also ask

Can a function return a Boolean value Python?

Functions can Return a Boolean.

Which Python function always returns a value?

Implicit return Statements A Python function will always have a return value. There is no notion of procedure or routine in Python. So, if you don't explicitly use a return value in a return statement, or if you totally omit the return statement, then Python will implicitly return a default value for you.

Which types of Python operators return Boolean as a result?

Because of this, True , False , not , and , and or are the only built-in Python Boolean operators.

Should functions always return the same type?

To meet the following two rules. Rule 1 -- a function has a "type" -- inputs mapped to outputs. It must return a consistent type of result, or it isn't a function.


2 Answers

I'm not aware of any built-in, but you can define them as:

false = lambda *_: False
true  = lambda *_: True
like image 156
enrico.bacis Avatar answered Oct 27 '22 08:10

enrico.bacis


You can use object, since its instances will always be treated as a true value, since object defines neither __len__, __nonzero__ (in Python 2), nor __bool__ (in Python 3).

>>> bool(object())
True
>>> if object():
...   print("Hi")
...
Hi
like image 33
chepner Avatar answered Oct 27 '22 08:10

chepner