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.
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 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.
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.
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.
I assume that typical path objects are either Path
s or str
s, as such you could use a Union
:
import pathlib
import typing
typing.Union[str, pathlib.Path]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With