简体   繁体   中英

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?

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

false = lambda *_: False
true  = lambda *_: True

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM