0

How do I validate if a variable is a valid class or type? I want to validate it before passing it into isinstance() Is there a way other than try catch? I'm using python2

J.Ku
  • 123
  • 7

1 Answers1

4

With regards to my comment:

classes and types are all instances of type, so to speak. That's why this will work:

>>> class foo():
    pass

>>> t = foo
>>> t
<class '__main__.foo'>
>>> isinstance(t,type)
True

EDIT - This works for Python3.x

On Python 2.x the class must be a new-style one (i.e. inherit from object)

class foo(object):
    pass
Pynchia
  • 10,996
  • 5
  • 34
  • 43
R Nar
  • 5,465
  • 1
  • 16
  • 32
  • I am afraid your answer works on Python3 only. The OP uses Python 2.7 – Pynchia Dec 14 '15 at 20:14
  • @Pynchia, that is a fair point that I always forget to take into account. Thank god for the dupe. edited to explicitly state this. – R Nar Dec 14 '15 at 20:17
  • BTW, the OP talks about variables/instances, I understand, not classes. i.e. `t=foo()`. And in such case, the above solution fails under python 2 (either using old-style or new-style classes. BTW, why are you using the parens in the class declaration?) – Pynchia Dec 14 '15 at 20:19
  • I use new style classes, so this solution seems to work fine even with python2.7 – J.Ku Dec 14 '15 at 20:25
  • no, he wants to ensure that the variable is a valid type to pass into as the second argument in `isinstance` so pretty much a type check to do a type check. – R Nar Dec 14 '15 at 20:25
  • Just doulble checked now: on python 2, it works only provided the class is a new-style one (i.e. `class foo(object):`) – Pynchia Dec 14 '15 at 20:44
  • @Pynchia yeah, I saw that in the dupe post so I figured I could just keep the answer up. and thanks for the edit – R Nar Dec 14 '15 at 20:47