Ashutosh Mishra Ashutosh Mishra - 2 years ago 63
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("")

I get output:

<class '_sre.SRE_Pattern'>

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

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

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

Answer Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download