Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to handle vat number validation

Tags:

python

I have a case where I want to validate an entered vat number. Each European country has a pre-defined format and I can create a regex pattern to validate an entered number.

My question is what would be the most "pythonic" way to handle this for 20 countries. Should I create a dictionary with each of the country and its pattern

Example

VAT_PATTERNS = {
   'ES': '([A-Z0-9][0-9]{7}[A-Z0-9]$)',
   'DE': '([0-9]{9}$)',
}

or is there a more pythonic way?

There are cases where several countries have the same pattern. Some countries might also have more complex patterns.

I could create a VAT base class from where each country's class inherits and handle it that way but that seems a bit out of place.

like image 672
Mikael Avatar asked Aug 21 '26 14:08

Mikael


2 Answers

Part of the "Zen of Python" (type import this into an interpreter!) is that "Explicit is better than implicit" and "Simple is better than complex".

What you've described looks both simple and explicit, and so I would consider it pretty pythonic.

like image 119
grifaton Avatar answered Aug 24 '26 03:08

grifaton


(I'm not sure there is a real answer to questions like this one -- what's "pythonic" and what is not is still much influenced by personal taste, IMHO. But since you ask for it, here's my take.)

The Zen of Python says:

Explicit is better than implicit. Simple is better than complex.

So, in your case, I'd say that a mapping country to VAT pattern, as you propose, is the simplest and most explicit solution, and therefore the most "pythonic" one.

like image 32
Riccardo Murri Avatar answered Aug 24 '26 05:08

Riccardo Murri