Typing: `object` vs `Any` (and `None` as a default)

I have a function with a parameter that represents an arbitrary value returned by a user defined function. Based on the typing docs, my understanding is that the correct typing for the value would be object instead of Any. Is that correct?

I want that the parameter to have None as a default value. Is it enough to use value: object = None or do I need to write value: object | None = None? I know you generally should explicitly specify None as a valid type, but because isinstance(None, object) is True that feels redundant.

I hadn’t thought of using object before - cheers.
It looks useful to me, to have the typechecker raise an error when I later try to do object.magic(). I’d say if you want that check, choose object. If you want the typechecker to ignore a possible call of a non-existent method, use Any.
Despite the redundancy, as a reader value: object | None = None tells me more about your intent, and if object is narrowed in future, the change is smaller.

2 Likes

Ultimately depends on what you will do with that parameter inside your function. Take into account that the docs say that type checking will be happy when your value: object gets assigned any value, but inside your function, when you want to use value to do other stuff, there will be few that will make the type checking happy.

I happened upon this StackOverflow discussion the other day: python - typing.Any vs object? - Stack Overflow

But as James says, I’m almost certain what you want here is Any.

1 Like