2

The documentation for typing.Any says

Changed in version 3.11: Any can now be used as a base class. This can be useful for avoiding type checker errors with classes that can duck type anywhere or are highly dynamic.

What kind of errors is this trying to avoid? At first, I thought the situation in mind was

class Foo:
    def __getattr__(self, attr: str) -> typing.Any:
        if attr == 'bar':
            return 5
        raise AttributeError(attr)

def print_bar(foo: Foo) -> None:
    print(foo.bar)

However, mypy 0.971 with Python 3.10.6 doesn't produce any errors.

Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
  • 1
    Oh, nice question. I'll probably retain from posting a full answer, but basically it allows you to create a *very* dynamic class that doesn't cause tons of type checking errors in places where it is used. Check out [this gist](https://mypy-play.net/?mypy=master&python=3.11&flags=strict&gist=874c489c457a30c5bab00e5454530c7b) (by me). – STerliakov Jul 28 '23 at 10:24
  • 1
    To be clear, this is intended for runtime. Before 3.11 you'll get `TypeError: Cannot subclass typing.Any` if you try `class MyClass(Any): pass`. – STerliakov Jul 28 '23 at 12:43

0 Answers0