You can subclass ‘typing.Any’

The spec calls out that you can create subclasses of ‘typing.Any’. Part of description confused me at first:

This can be useful for avoiding type checker errors with classes that can duck type anywhere or are highly dynamic.

I first read this to mean that a subclass of ‘Any’ should be treated as another way to spell the Any type. That would lead to:

Every type is assignable to [each subclass of ‘Any’], and [each subclass of ‘Any’] is assignable to every type.

The correct reading is to start from first principles. The Any type means “we don't know”, and so a class that inherits from ‘Any’ has a superclass, but we don't know precisely which one.

That means that only half of the above is correct. An instance of a subclass of ‘Any’ is assignable to every type ‘T’, since we can materialize the ‘Any’ superclass to ‘T’, and an instance of a class is assignable to a variable of that class of any of its superclasses.

But the converse is not true. The following does not type-check:

class Sub(Any):
    pass

x: Sub = 4

because the following does not either:

class Sub(int):
    pass

x: Sub = 4

(You can assign to a superclass-typed variable, but not to a subclass-typed variable. Liskov substitutability. The “assignable from” relation is not symmetric.)

Open question

Links

=> Take 2: Rules for subclassing Any [Python Discourse]

=> The Any type | » Languages » Python » Typing

Proxy Information
Original URL
gemini://dcreager.net/languages/python/typing/subclass-any.gmi
Status Code
Success (20)
Meta
text/gemini;lang=en
Capsule Response Time
409.709799 milliseconds
Gemini-to-HTML Time
1.009738 milliseconds

This content has been proxied by September (3851b).