pythonpython-typingpathlib

What is the correct way in python to annotate a path with type hints?


What is the proper way to annotate this simple utility function in python3 that reads from a file? It should accept pathlib.Path objects as well as any other common way of passing a path.

def read_json(path: <TYPE HINT>):
    with open(path, 'rb') as f:
        data = json.load(f)
    return data

It seems to me as if this topic is in flux and I couldn't find a good place where this information was collected. I am interested in how to handle this in python 3.6, 3.7 and 3.8.


Solution

  • I assume that typical path objects are either Paths or strs, as such you could use a Union. In addition, the more inclusive os.PathLike is preferred over pathlib.Path.

    Python 3.10 or newer:

    import os
    
    def read_json(path: str | os.PathLike):
        ...
    

    Python 3.6 - 3.9:

    import os
    import typing
    
    def read_json(path: typing.Union[str, os.PathLike]):
        ...