Type hinting highly dynamic functions

Getting into typing and I have a couple of methods that are highly dynamic such as getters or setters that take Any and return Any.

def get(self, key: Any, default: Any) -> Any:
    pass

Are these worth annotating, or should I leave them without annotations?

There’s also examples like this:


def _str_get(self, key: str, default: Any) -> Any:
    pass

_str_get() is guarded by an isinstance check (in my particular code base), would I type annotate the key parameter in that method under such conditions?

Thanks all. :slightly_smiling_face:

I forgot to mention one thing, what about methods such as __repr__, should it be typed as returning a str, or is that considered unnecessarily verbose?

Many people who use static type analysis prefer to be able to tell the difference between these two situations:

  • “I’ve thought about the types for this, and it is highly dynamic.”
  • “I haven’t thought about the types for this, or I’ve forgotten about it.”

If you don’t put the Any there, then you can’t tell the difference between these two.

For your get function, @overload may be something worth looking into (mypy docs)

For __repr__, I think it is not necessary to type, but I won’t say it is overly verbose if you do. Type checkers already understand that your subclass’s __repr__ overloads object’s __repr__, which should return str.