Change 'is' operator slightly

A thing I thought of recently is how to check the type of an object, you typically use type(obj) is ... or isinstance(obj, ...), and how the is operator could be changed a little bit to provide a shorthand way of writing this. For one if statement, it wouldn’t be that big of a change, but if you are checking the types of items a lot (for example, for a type checker), it would save some time overall. The new syntax would look something like this:

if [1, 2, 3] is list: # instead of 'isinstance([1, 2, 3], list)'
  print("[1, 2, 3] is a list!")
else:
  print("Not a list")

A thing I thought of recently is how to check the type of an object,
you typically use type(obj) is ...

This is quite rare, and usually discouraged.

or isinstance(obj, ...),

Yes.

and how the is operator could be changed a little bit to provide a
shorthand way of writing this. For one if statement, it wouldn’t be
that big of a change, but if you are checking the types of items a lot
(for example, for a type checker), it would save some time overall. The
new syntax would look something like this:

if [1, 2, 3] is list: # instead of 'isinstance([1, 2, 3], list)'
 print("[1, 2, 3] is a list!")
else:
 print("Not a list")

This won’t fly I’m afraid. Types are also first class objects and
existing use of “is” with a type is perfectly sane. Which means you
can’t change it.

2 Likes

Exactly what Cameron said!

Note also that type(obj) is cls is different from isinstance(obj, cls):

class A: ...
class B(A): ...
b = B()
print(isinstance(b, A))
print(type(b) is A)

It’s perfectly reasonable to check two types for identity, for instance when testing for Py2/Py3:

if str is bytes:

Since types are themselves objects, every operation valid on an object is by definition valid on a type.

The way you would ask, in English, is [1, 2, 3] is a list. It would be a pain to have a as a keyword.
Maybe is_a could do it.

The way you would ask, in English, is [1, 2, 3] is a list .

Interesting. I actually did not think of it this way, and thought this was more accurate.

Maybe is_a could do it.

I guess that could work, since it makes the syntax of is still simple, and since a wouldn’t be a keyword (which would more than break existing code), it provides a simple and readable solution.