Search code examples
pythontype-hinting

What type hint should I write when the return type is uncertain?


For example, if I define this function:

def open_pkl(src: str) -> ?:
    with open('serialized.pkl', 'rb') as f:
        data = pickle.load(f)
    return data

what type hint should I write for the return value?

Now, I write the function as:

def open_pkl(src: str):
    with open('serialized.pkl', 'rb') as f:
        data = pickle.load(f)
    return data

Is there type a hint for an uncertain return type?


Solution

  • There are two options: object and typing.Any. Returning an object signals to the caller of the function that nothing can be assumed about the returned object (since everything is an object, saying that something is an object gives no information). So, if a user were to do

    def open_pkl(src: str) -> object:
        ...
    
    something = open_pkl('some/file')
    print(len(something))
    

    that would be a type violation, even if the object were a list, because objects per se don't have a __len__ method.

    typing.Any, on the other hand, is like a wild card which could hypothetically be anything. So, if you reworked the above example to have a typing.Any return type, there would be no type violation. Does a typing.Any have a __len__ method? Maybe. Who says it couldn't?

    To summarize, you should use object if you want to "force" (because type hints are just suggestions) your users to verify the type of any object returned by this function. Use typing.Any to be more lax.