Skip to content

TYP: Add type hints for Literal types #2812

@seisman

Description

@seisman

Literal Types indicate a variable has a specific and concrete value. It was introduced in PEP 586 and is available since Python 3.8.

I'll take the pygmt.datasets.load_earth_relief function as an example. Currently, the function definition is:

def load_earth_relief(
    resolution="01d",
    region=None,
    registration=None,
    data_source="igpp",
    use_srtm=False,
)

in which, registration can be gridline, pixel or None, and data_source can be igpp, gebco, gebcosi, synbath.

To add Literal type hints for these two parameters, we need to change the function definition to:

from typing import Literal

def load_earth_relief(
    resolution="01d",
    region=None,
    registration: Literal["gridline", "pixel", None] = None,
    data_source: Literal["igpp", "gebco", "gebcosi", "synbath"] = "igpp",
    use_srtm=False,
)

We also need to remove the "type" from the docstrings (e.g., changing registration : str to registration (see https://www.sphinx-doc.org/en/master/usage/extensions/example_numpy.html).

After adding Literal type hints, most text editors and IDEs can provide better autocompletion for the valid values. For example (please ignore the incorrect registration="registration" code in the demo below. It's caused by a typo):

autocompletion-valid-values.mov

TODO

Some notes:

  1. For each PR, we should work on a single parameter used by multiple functions (e.g., updating registration in all load_earth_xxx functions), rather than working on multiple parameters in a single function (e.g., updating registration and data_source in the load_earth_relief function). I think it will make the review much easier.
  2. Focus on parameters listed in function definitions (e.g., registration in load_earth_relief) rather than GMT's aliased parameters (e.g., registration in pygmt.xyz2grd, which is aliased to the -r option). Type hints for these aliased parameters need more discussions.
  3. Some parameters may have a long list of valid values (e.g., load_earth_relief's resolution parameter can have 15 valid values). Need to discuss if we should add such a long list Literal values.

Here is an incomplete list of parameters that we should add Literal type hints. **Please add your name to the end of the entry if you wan to work on it (in case you can edit this post) or just leave a comment so that we know you're working on it).

References:

Metadata

Metadata

Assignees

No one assigned

    Labels

    typingType hints and static type checking

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions