0

The following code Prints False:

from enum import Enum
type_ = str
print(issubclass(type_, Enum))

The following code prints True:

from enum import Enum
type_ = Enum('MyEnum', {'a': 1, 'b': 2})
print(issubclass(type_, Enum))

The following code throws an error:

from enum import Enum
from typing import List
type_ = List[str]
print(issubclass(type_, Enum))
# TypeError: issubclass() arg 1 must be a class

Is there a better way than a try / except to check that an object is a class definition? Something like:

print(isclass(type_) and issubclass(type_, Enum))
tofarr
  • 7,682
  • 5
  • 22
  • 30
  • `issubclass(type(your_object_here), type)`? – Brian61354270 Mar 17 '23 at 16:51
  • 2
    `isinstance(some_object, type)` – juanpa.arrivillaga Mar 17 '23 at 16:52
  • 2
    Why is `Enum` involved here at all? What does `Enum` have to do with anything? – user2357112 Mar 17 '23 at 16:53
  • 1
    Terminology note: you want to check if an object is a *class*/*type* (those are synonyms in Python 3, not back in the day, but the unification was a big part of the Python 3 release). A "class definition" is the actual syntactic construct. That eventually calls the type constructor, i.e. `type(..., ..., ...)` to create an instance of `type` – juanpa.arrivillaga Mar 17 '23 at 16:54
  • You can import `isclass` from `inspect` – flakes Mar 17 '23 at 16:54
  • 4
    @flakes no need. You just want `isinstance(obj, type)` the old `isclass` used to be necessary when there were old-style and new-style classes – juanpa.arrivillaga Mar 17 '23 at 16:55
  • Is the `Enum` stuff here because you're trying to check whether an object is a class so you know whether you can safely call `issubclass(thing, Enum)`, or were you thinking that `issubclass(type_, Enum)` should somehow be part of checking whether an object is a class? – user2357112 Mar 17 '23 at 16:56
  • @juanpa.arrivillaga Ah neat. I thought it was there just for readability. Wasn't doing any meta-programming like this when 2.7 was used more. – flakes Mar 17 '23 at 16:57

0 Answers0