Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Note to self:
- #Python's isinstance() function's main mission is to make your life a living hell when working with booleans and integers.
- #---IsInstance example---
- #Behavior: The Boolean will be seen as an Integer
- #This will print "I'm an integer" even though we clearly define isBoolean as a boolean on the next line
- isBoolean = True
- if isinstance(isBoolean, int):
- print "I'm an integer"
- elif isinstance(isBoolean, bool):
- print "I'm a boolean"
- #Reason: Logically, Python is correct in its logic since booleans are represented as 1s & 0s on a primitive level.
- #However, since isinstance() appears to evaluate underlying value, not the visible representation, it can cause hours of headaches.
- #---Solution for the IsInstance boolean/integer woes---
- #Using type() and directly comparing to a type
- #This will give us the expected behavior of evaluating a boolean as a boolean and not as an integer
- isBoolean = True
- if type(isBoolean) is int:
- print "I'm an integer"
- elif type(isBoolean) is bool:
- print "I'm a boolean"
Advertisement
Add Comment
Please, Sign In to add comment