2 ms·
> There's no type casting in Python. If you search "type casting in Python" you will find lots of articles explaining how to use int(), str(), etc. to cast. Th
by crazygringo 1y ago
> There's no type casting in Python.
If you search "type casting in Python" you will find lots of articles explaining how to use int(), str(), etc. to cast. This is a common and well-documented concept, even if it's different under the hood from e.g. C.
The idea that you'd name a function bool() and have it act differently is a deeply confusing design decision that it's understandable people would get misled by and frustrated with. This is a function named after a fundamental type. It's not a random user-defined constructor.
- bb88 1y agoIf we do it that way, we have worse problems. if "False": # What do you expect? True or False? print("True") else: print("False") bool() is consistent with how "truthiness" happens in python. Otherwise we end up with the YAML norway problem. if bool("False"): print("True") else: print("False") # This would be different if we landed here. And that would be different behavior then the above -- creating a nasty inconsistency. Honestly it's not that hard to write something that looks like this: def str_to_bool(val: str) -> bool: return val.lower() in ["yes", "true", "1"]
- jonathrg 1y agobool() is not a function named after a fundamental type. bool is a type. As with any type, you can call bool(...) to construct a new object of that type. https://docs.python.org/3/library/functions.html#bool https://docs.python.org/3/library/functions.html#bool A good tutorial will reflect this fact and use appropriate language. Both the idea that you can "cast", and the idea that bool is a function, are misunderstandings rooted in the idea that Python should be like C in all ways.