caffeinatedmike

Python's IsInstance() Woes

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