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
Asked
Active
Viewed 291 times
0

J.Ku
- 123
- 7
-
2How would a variable not be of any valid type? – timgeb Dec 14 '15 at 19:52
-
2Isn't that why you would use isinstance? – Padraic Cunningham Dec 14 '15 at 19:53
-
say for example if I do isinstance(a, {}), i will get a type error. I want to make sure the second parameter I pass into isinstance is valid. – J.Ku Dec 14 '15 at 19:55
-
2use `isinstance(var, type)` since `type` is a `type`. which sounds weird. – R Nar Dec 14 '15 at 19:56
-
ok! This takes care of the type. Is there a way to determine it is it a valid class then? – J.Ku Dec 14 '15 at 19:58
-
will still work the same way. – R Nar Dec 14 '15 at 19:58
1 Answers
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, 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