Bottom Page

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)?
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Quote
#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)
Quote
#3
isinstance(foo,type(bar)) ?
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Quote
#4
Now you are changing the specifications. What if bar has a subtype of type(foo)?
Quote
#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))
My code examples are always for Python >=3.6.0
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Quote
#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.
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Quote

Top Page

Forum Jump:


Users browsing this thread: 1 Guest(s)