Ashutosh Mishra Ashutosh Mishra - 7 months ago 20
Python Question

When type([object]) is used in an if statement, why must it be typecasted into a string?

When I execute the following code:

import re
phoneNumRegex = re.compile("")
print(type(phoneNumRegex))


I get output:

<class '_sre.SRE_Pattern'>


However, if I try and use
type(phoneNumRegex)
in an if statement, I need to typecast it into a
str
for it to work as intended:

if str(type(phoneNumRegex)) == "<class '_sre.SRE_Pattern'>":
print("This if statement works")


Note how it reads
str(type(phoneNumRegex))
above, not
type(phoneNumRegex)
. My question is, why must I typecast
type(phoneNumRegex)
into a
str
when I use it in an if statement?

Answer

That's because the type() function returns a type object:

>>> type(type(phoneNumRegex)) 
<type 'type'>

A better way to check if a variable is of a certain type is using isinstance(). In case of a regular expression pattern type: