Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to call a function inside python's match pattern?

I have code

join_prefix = lambda text: config.get("CM_PREFIX") + text

match shlex.split(message.message):
    case [join_prefix("setmode"), mode] if mode.isdigit():
        await self._set_mode_handler(message, int(mode))
        return
    case [join_prefix("getmode")]:
        await self._get_mode_handler(message)
        return

mode is not defined, so it is used for list unpacking.
But python throws an error:

    case [join_prefix("getmode")]:
TypeError: called match pattern must be a type

How do i call a function inside match pattern?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The pattern is not an expression, so you cannot build up a pattern dynamically with other expressions at runtime. In fact, [join_prefix("setmode"), mode] is not a list; it’s a sequence pattern consisting of a class pattern join_prefix("setmode") and a capture pattern mode.

Instead, you need to match against a namespace you define before the match statement with a value pattern (which, roughly speaking, is a dotted name, not a simple name). For example,

from types import SimpleNamespace


modes = SimpleNamespace(
    set=join_prefix("setmode"),
    get=join_prefix("getmode")
)


match shlex.split(message.message):
    case [modes.set, mode] if mode.isdigit():
        ...
    case [modes.get]:
        ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading