Defining “boolness” of a class in python

For Python 2-3 compatibility, add a line after the class definition block to alias the method: class Foo(object): … Foo.__nonzero__ = Foo.__bool__ or include the alias directly in the class definition: class Foo(object): def __bool__(self): … __nonzero__ = __bool__ Of course this would also work the other way around, but I think the name __nonzero__ … Read more

What is the difference between Convert.ToBoolean(string) and Boolean.Parse(string)?

Convert.ToBoolean(string) actually calls bool.Parse() anyway, so for non-null strings, there’s no functional difference. (For null strings, Convert.ToBoolean() returns false, whereas bool.Parse() throws an ArgumentNullException.) Given that fact, you should use bool.Parse() when you’re certain that your input isn’t null, since you save yourself one null check. Convert.ToBoolean() of course has a number of other overloads … Read more

Get random boolean true/false in PHP

If you don’t wish to have a boolean cast (not that there’s anything wrong with that) you can easily make it a boolean like this: $value = rand(0,1) == 1; Basically, if the random value is 1, yield true, otherwise false. Of course, a value of 0 or 1 already acts as a boolean value; … Read more

Is there a parsing of bool like int in Dart?

Bool has no methods. var val=”True”; bool b = val.toLowerCase() == ‘true’; should be easy enough. With recent Dart versions with extension method support the code could be made look more like for int, num, float. extension BoolParsing on String { bool parseBool() { return this.toLowerCase() == ‘true’; } } void main() { bool b … Read more

How to create a boolean value?

The value of the $var variable as defined in:    <xsl:variable name=”var” select=”boolean(‘false’)”/> is    true() This is because in XPath “false” is an ordinary string, as opposed to false(), which is the constructor for the boolean value false() The two boolean values in XPath are (note that they are constructed!):    true() and false() The detail of … Read more

C++ printing boolean, what is displayed?

The standard streams have a boolalpha flag that determines what gets displayed — when it’s false, they’ll display as 0 and 1. When it’s true, they’ll display as false and true. There’s also an std::boolalpha manipulator to set the flag, so this: #include <iostream> #include <iomanip> int main() { std::cout<<false<<“\n”; std::cout << std::boolalpha; std::cout<<false<<“\n”; return … Read more

How do I concatenate a boolean to a string in Python?

answer = True myvar = “the answer is ” + str(answer) Python does not do implicit casting, as implicit casting can mask critical logic errors. Just cast answer to a string itself to get its string representation (“True”), or use string formatting like so: myvar = “the answer is %s” % answer Note that answer … Read more