Make your API better with this positional trick from Python 3.8

Explore positional-only parameters and two other underutilized but still useful Python features.
62 readers like this.
Women in computing and open source v5

kris krüg

This is the ninth in a series of articles about features that first appeared in a version of Python 3.x. Python 3.8 was first released in 2019, and two years later, many of its cool new features remain underused. Here are three of them.

importlib.metadata

Entry points are used for various things in Python packages. The most familiar are console_scripts entrypoints, but many plugin systems in Python use them.

Until Python 3.8, the best way to read entry points from Python was to use pkg_resources, a somewhat clunky module that is part of setuptools.

The new importlib.metadata is a built-in module that allows access to the same thing:

from importlib import metadata as importlib_metadata

distribution = importlib_metadata.distribution("numpy")
distribution.entry_points
    [EntryPoint(name='f2py', value='numpy.f2py.f2py2e:main', group='console_scripts'),
     EntryPoint(name='f2py3', value='numpy.f2py.f2py2e:main', group='console_scripts'),
     EntryPoint(name='f2py3.9', value='numpy.f2py.f2py2e:main', group='console_scripts')]

Entry points are not the only thing importlib.metadata permits access to. For debugging, reporting, or (in extreme circumstances) triggering compatibility modes, you can also check the version of dependencies—at runtime!

f"{distribution.metadata['name']}=={distribution.version}"
    'numpy==1.20.1'

Positional-only parameters

After the wild success of keywords-only arguments at communicating API authors' intentions, another gap was filled: positional-only arguments.

Especially for functions that allow arbitrary keywords (for example, to generate data structures), this means there are fewer constraints on allowed argument names:

def some_func(prefix, /, **kwargs):
    print(prefix, kwargs)
some_func("a_prefix", prefix="prefix keyword value")
    a_prefix {'prefix': 'prefix keyword value'}

Note that, confusingly, the value of the variable prefix is distinct from the value of kwargs["prefix"]. As in many places, take care to use this feature carefully.

Self-debugging expressions

The print() statement (and its equivalent in other languages) has been a favorite for quickly debugging output for over 50 years.

But we have made much progress in print statements like:

special_number = 5
print("special_number = %s" % special_number)
    special_number = 5

Yet self-documenting f-strings make it even easier to be clear:

print(f"{special_number=}")
    special_number=5

Adding an = to the end of an f-string interpolated section keeps the literal part while adding the value.

This is even more useful when more complicated expressions are inside the section:

values = {}
print(f"{values.get('something', 'default')=}")
    values.get('something', 'default')='default'

Welcome to 2019

Python 3.8 was released about two years ago, and some of its new features are cool—and underused. Add them to your toolkit if you haven't already.

What to read next
Tags
Moshe sitting down, head slightly to the side. His t-shirt has Guardians of the Galaxy silhoutes against a background of sound visualization bars.
Moshe has been involved in the Linux community since 1998, helping in Linux "installation parties". He has been programming Python since 1999, and has contributed to the core Python interpreter. Moshe has been a DevOps/SRE since before those terms existed, caring deeply about software reliability, build reproducibility and other such things.

Comments are closed.

Creative Commons LicenseThis work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License.