Make your API better with this positional trick from Python 3.8 | Opensource.com

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.

Women in computing and open source v5
Image credits : 
kris krüg
x

Subscribe now

Get the highlights in your inbox every week.

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.

Hands on a keyboard with a Python book

Explore some of the underutilized but still useful Python features.
Python programming language logo with question marks

Explore some of the underutilized but still useful Python features.
Business woman on laptop sitting in front of window

Explore some of the underutilized but still useful Python features.
Coding on a computer

Explore exception handling and other underutilized but still useful Python features.
old school calculator

Plus explore some of the underutilized but still useful Python features.
Hacker code matrix

Explore some of the underutilized but still useful Python features.
Computer screen with files or windows open

Explore os.fspath and two other underutilized but still useful Python features.
Hands on a keyboard with a Python book

Learn more about this and two other underutilized but still useful Python features.

Topics

About the author

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 Zadka - 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. He has worked in companies as small as three people and as big as tens of thousands -- usually some place around where software meets system administration...