Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 848
Zacharias030 Avatar asked Oct 24 '19 12:10

Zacharias030


People also ask

How do you type hinting in Python?

Here's how you can add type hints to our function: Add a colon and a data type after each function parameter. Add an arrow ( -> ) and a data type after the function to specify the return data type.

What is type annotation in Python?

What Are Type Annotations? Type annotations — also known as type signatures — are used to indicate the datatypes of variables and input/outputs of functions and methods. In many languages, datatypes are explicitly stated. In these languages, if you don't declare your datatype — the code will not run.

Should you use type hints in Python?

In his excellent article The State of Type Hints in Python, Bernát Gábor recommends that “type hints should be used whenever unit tests are worth writing.” Indeed, type hints play a similar role as tests in your code: they help you as a developer write better code.

Does Python enforce type hints?

Python will always remain a dynamically typed language. However, PEP 484 introduced type hints, which make it possible to also do static type checking of Python code. Unlike how types work in most other statically typed languages, type hints by themselves don't cause Python to enforce types.


1 Answers

I assume that typical path objects are either Paths or strs, as such you could use a Union:

import pathlib
import typing

typing.Union[str, pathlib.Path]
like image 59
Christian Sauer Avatar answered Oct 12 '22 09:10

Christian Sauer