Python Forum

Full Version: comparing types
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
my function gets 2 arguments, foo and bar. they need to be the same type. verifying this is pretty obvious:
if type(foo) is type(bar):
    ...
or should i use == instead of is? is this the right way to go (ignoring those who say i should only support one type)?
It is the right way to go. Observe that it will also return False if for example type(foo) is a subclass of type(bar)
isinstance(foo,type(bar)) ?
Now you are changing the specifications. What if bar has a subtype of type(foo)?
There is a issubclass built-in.

class Bar: ...
class Foo(Bar): ...

foo_inst = Foo()
bar_inst = Bar()
type(bar_inst) in type(foo_inst).mro()


# but easier is the subclasscheck
issubclass(type(foo_inst), type(bar_inst))
(Jun-26-2020, 07:08 AM)Gribouillis Wrote: [ -> ]Now you are changing the specifications. What if bar has a subtype of type(foo)?

if either is a subtype of the other. i'll have to decide if that should be considered the same. i need another value for bool ... Maybe. if i make this into a function, it could return 3 different int values.