Skip to main content

Use top-level variable references in match cases

Project description

Match-Ref

Top-Level Variable References For Python's match

zero dependencies PyPI - Python Version PyPI


Objective

This library provides a convenient interface to variables in the local and global namespaces, using qualified (dotted) names.

Python 3.10 introduced the match-case structure which allows you to write flow control code like this:

my_choice = input("Your choice: ")
fruit_on_sale = "peach"

match my_choice:
    case "apple": print("Delivering an apple.")
    case "banana": print("Delivering a banana.")
    case fruit_on_sale:
        print("Good choice!")

If you now entered a value like tomato, he output would be fruit_on_sale. This is, because fruit_on_sale is considered a placeholder/capture pattern and not a reference to a variable.

Therefore, we need another way to reference variables. We can accomplish this using dotted names (i.e. fruit_data.fruit_on_sale, because Python does not interpret these names as placeholders.

Installation

You can install this package using pip :

  • pip install match-ref on all platforms, if available
  • python3 -m pip install match-ref on Unix
  • py -m pip install match-ref on Windows

Usage

from matchref import ref

my_choice = "banana"
fruit_on_sale = "peach"
match my_choice:
    case ref.fruit_on_sale: print("Good choice!")

You can use the ref helper to resolve all variables in the current local and global namespaces which you could usually reference without using a dotted name.

You can use ref.any_local_or_global_variable_name in any expression, not only inside case conditions, if you need to.

Only value retrieval is supported, as attribute-setting is not the purpose of this library.

How does it work?

ref is the default instance of the ScopeReference class, defined in match-ref. It has a method __getattr__ which gets called whenever you request an attribute of ref. This method then starts looking up the local namespace it was called from (your script or your function) and, if it doesn't find the variable you're looking for, continues searching the global namespace as well.

If it doesn't find the variable you are looking for, the following error is being raised:

ValueError: referenced name '...' is not defined

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

match-ref-1.0.1.tar.gz (3.1 kB view hashes)

Uploaded Source

Built Distribution

match_ref-1.0.1-py3-none-any.whl (3.1 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page