Distinction between “class” and “type”

Paul Rubin no.email at nospam.invalid
Fri May 13 02:42:34 EDT 2016


Ben Finney <ben+python at benfinney.id.au> writes:
>     There's a big overlap because most classes are also types -- but not
>     the other way around! E.g. Any is a type but not a class (you can
>     neither inherit from Any nor instantiate it), and the same is true
>     for unions and type variables. […]

> As a Bear of Little Brain, this leaves me clueless. What is the
> distinction Guido alludes to, and how are Python classes not also types?

I thought I understood Guido's explanation but maybe I missed something.

Let C be a class, maybe defined by a class statement or maybe a builtin
like "int".  You can make an instance of C the usual way:

   x = C()

And you can have a type annotation that says function f expects an
arg that is an instance of C:

   def f(x : C) -> int: ...

You might alternatively write a function whose arg must be either an int
or a string:

   def f(s : Union[int, str]) -> int : ...

or (I think, I haven't tried it) you can equivalently bind that type to
a variable:

   T = Union[int, str]
   def f(s : T) -> int : ...

The point here is that T is a type but it is not a class.  You can't
instantiate T by saying

   x = T()

and expecting to get back some value that is (indeterminately) an int or
a string.

That is, there's stuff (like instantiation) that you can do with types
that happen to be classes, but there are also types that aren't classes.



More information about the Python-list mailing list