0

I have a function that will do various regex-matches to find out which courier belongs to the provided tracking-id.

Right now, I'm using many elif statements which works fine but I got the feeling that this isn't very scalable in terms of maintanance.

import re


def get_courier(tracking_id):
    """ Retrieves the courier from a given tracking-id """

    if re.match(r'^ABC\d*$', f'{tracking_id}'):
        courier = "Courier 1"
    elif re.match(r'^\d*-\d$', f'{tracking_id}'):
        courier = "Courier 2"
    elif re.match(r'^PREF\d*$', f'{tracking_id}'):
        courier = "Courier 3"
    # ...
    else:
        courier = None

    return courier

Would there be a possibility to maybe "outsource" the patterns into a file or database where I can define the patterns and their related courier?

I can't get my head around a solution that could work like this

import re


def get_courier(tracking_id):
    """ Retrieves the courier from a given tracking-id """

    patterns = database_select_function()

    courier = re.match(patterns, tracking_id)

    return courier
2
  • What is in tracking_id? Commented Jan 8, 2021 at 11:27
  • tracking_id will be an (alphanumeric) string like ABC123456 or 123-456 Commented Jan 8, 2021 at 11:30

1 Answer 1

1

A simple better solution for regex pattern matching in python is the following:

import re

courier_patterns={r'^ABC\d*$': 'Courier 1',
                  r'^\d*-\d$': 'Courier 2',
                  r'^PREF\d*$': 'Courier 3'}

def get_courier(tracking_id):
    """ Retrieves the courier from a given tracking-id """

    courier=None

    for pattern, courier_name in courier_patterns.items():
        if re.match(pattern):
            courier=courier_name
            break

    return courier

As you can see, I'm not loading courier patterns from file or DB, but adapting this solution is simple.

Sign up to request clarification or add additional context in comments.

3 Comments

would have been nicer should you extract the matching logic into a separate more generic function (that possibly accepts the set of patterns and the string)
@Tibebes.M Please explain better or give your answer. I'm curious and I want to improve my code.
That's brilliant thanks Stefano! The loop through .items() is exactly what I was missing. The rest will be done relatively easy as you already said! :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.