0

I am working on a script that checks format of data files ( like csv)

I apply various rules on each field: max length , empty field, value boundery, regex to match (check valid emails) etc...

These rules a in a dictionary (each collum have is one) :

#column 1 : integer from 1 to 99, except 10
{
"minval":1,
"forbiddenvals": [10,15],
"maxval":100
}

My function definition is the following :

def vercol(data,
           empty=False,isadate = None,
           minlen=None,maxlen=None,
           minval=None,maxval=None,
           allowedvals=[],forbiddenvals=[],
           regex =None):
    """
    Verify if the field 'data' checks the rules
    
    Parameters /Rules
    ----------     
    empty : Boolean, optional
        set to True if empty field is accepted. The default is False.      
    minlen : integer, optional
        If set, minimum length for the field.    
    maxlen : integer, optional
        If set, maximum length for the field.       
    forbidenvals : List, optional
        List of rejected values.
    (...)

    Returns
    -------
    True if all the rules are met. 
    "xError" if a test failled, where x depend of the wich test failed FIRST
    """
    
    if data == "":
        return True if empty else "EmptyFieldError" 
    if minlen and len(data) < int(minlen):
        return "MinLengthError"
    ....
    other rules
    ....
    return True

The function works without fine when I call parameters normally:

What I want to do is to pass the dictionary like this :

rules = {
    "minval":1,
    "forbiddenvals": [10,15],
    "maxval":100
    }
result = vercol(field, rules)
#foo

Problem: it doesn't work, the parameters only use their default value despite being in the dict.

#works fine
vercol('abcdefghi', maxlen=4) #return "MaxLenError"
vercol('', maxlen=4) #return "EmptyFieldError"
vercol('', empty=True) #return True

#problem 
rule = {"maxlen":4,"empty":False}
vercol('',rule) #retuns True , expected : "EmptyFieldError"
vercol('abcdefgh',rule) #retuns True , expected : "MaxLenError"

Any clue to solve this ?

Martial P
  • 395
  • 1
  • 12

1 Answers1

0

You have to unpack the dict using **. Just try

rules = {
    "minval":1,
    "forbiddenvals": [10,15],
    "maxval":100
    }
result = vercol(field, **rules)
ynotzort
  • 326
  • 2
  • 6