Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
comparing types
#1
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)?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
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)
Reply
#3
isinstance(foo,type(bar)) ?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#4
Now you are changing the specifications. What if bar has a subtype of type(foo)?
Reply
#5
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))
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#6
(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.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020