1

I have a variable x and whose type is :

type(x)
>> <class '__main__.XmlListConfig'>

in the next part, I want to see if the type of x is <class'__main__.XmlListConfig'> I am unable to compare and see it So far, I have tried:

if type(x) == "__main__.XmlListConfig":

This does not work because ofcourse I am comparing it to a string. Any Suggesting will help and please feel free to ask me for more clarification.

User2939
  • 165
  • 7
  • 1
    Look at the type's `__name__` attribute. This is a terrible code smell, though, because it removes what little type safety Python provides. – erip Aug 16 '18 at 17:11
  • 6
    `isinstance(x, XmlListConfig)` - or, in the unlikely event you want an exact type check rather than accepting subclasses: `type(x) is XmlListConfig`. – jasonharper Aug 16 '18 at 17:12
  • more info about `isinstance` and `type`: https://stackoverflow.com/questions/1549801/what-are-the-differences-between-type-and-isinstance – Lasha Kitia Aug 16 '18 at 17:13

1 Answers1

1

To get around the string comparison problem you could try

if str(type(x)) == "<class '__main__.XmlListConfig'>":
    do_stuff()

although that is inconsistent and hard to read, so better to use isinstance:

if isinstance(x, XmlListConfig):
    do_stuff()
natonomo
  • 325
  • 1
  • 9