2

What is wrong with this code and is that implementation correct?

from enum import Enum

class Test(object):
    Filters = Enum('Filters', 'A B C')  
    def __init__(self):
        pass

    def aaa(self, filters):
        if(isinstance(filters, self.Filters.B)):
            print 'OK'
        else:
            print 'NOT OK'
if __name__ == '__main__':
    Test().aaa(Test.Filters.B)

Error is:

Traceback (most recent call last):
  File "test.py", line 14, in <module>
    Test().aaa(Test.Filters.B)
  File "test.py", line 9, in aaa
    if(isinstance(filters, Test.Filters.B)):
TypeError: isinstance() arg 2 must be a type or tuple of types
1
  • Have you tried to execute it? if no, whats the error message? Commented Feb 19, 2016 at 10:48

3 Answers 3

3

If you want to know if the filters parameter is a member of the Test.Filters Enum, you have three choices

  • isinstance(filters, Test.Filters)
  • filters in self.Filters

(Test and self are interchangeable.)

If you want to know if the filters parameter is Test.Filters.B then a simple comparison will work:

filters is self.Filters.B
Sign up to request clarification or add additional context in comments.

1 Comment

Used this for IronPython: filters in self.Filter
2

The error you get is quite clear:

TypeError: isinstance() arg 2 must be a type or tuple of types

Filters.B is not a class or type. Instead of using isinstance, just compare the value that you got with the one you want:

if filters is Test.Filters.B:

Also, Filters is an attribute of the class, not of the instance, so you should probably rather use Test.Filters, although self.Filters seems to work, too.

Comments

-1
self.Filters.B 

is not defined. You defined

Filters.B

Also:

self.Filters.B

needs to be:

type(self.Filters.B)

it works like this:

class A():
    pass

isinstance(3, int) == True
isinstance(3,type(4)) == True
isinstance("hello", type('something')) == True
isinstance("hello", str) == true
isinstance(A(), type(A())) == True
isinstance(A(), A) == True

6 Comments

Nope, that's not the problem.
i don't get it. How to fix it, or even better. How should that be made correctly?
Note that using if isinstance(filters, type(self.Filters.B)) (or whatever exactly you did, it's not really clear from the answer) will only check whether filters is a Filter, not whether it's Filter.B. Try passing Fitler.A as parameter.
isinstance(A(), type(A)) == True wrong! type(A) is type. You can do either isinstance(A(), A) or type(A()) == A, but isinstance(A(), type(A)) won't work.
THANKS guys for all the help and details! You are awesome! I've finally got that!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.