Question

How can I iterate through my arguments to print these lines out for each of the arguments in my function, instead of typing each of them out?

def validate_user(surname, username, passwd, password, errors):

    errors = []

    surname = surname.strip() # no digits
    if not surname:
        errors.append('Surname may not be empty, please enter surname') 
    elif len(surname) > 20:
        errors.append('Please shorten surname to atmost 20 characters')

    username = username.strip()
    if not username:
        errors.append('Username may not be empty, please enter a username') 
    elif len(surname) > 20:
        errors.append('Please shorten username to atmost 20 characters')
Was it helpful?

Solution

Form a list of those arguments:

def validate_user(surname, username, passwd, password, errors):
    for n in [surname, username]:
        n = n.strip()
        # Append the following printed strings to a list if you want to return them..
        if not n:
            print("{} is not valid, enter a valid name..".format(n))
        if len(n) > 20:
            print("{} is too long, please shorten.".format(n))

I should note this is really only valid for simple surname or username validation.

OTHER TIPS

what you really want is locals.

def f(a, b, c):
    for k, v in locals().items():
        print k, v

or something like that.

In addition to all the answers, you can use the inspect library

>>> def f(a,b,c):
...   print inspect.getargspec(f).args
...
>>> f(1,2,3)
['a', 'b', 'c']
>>> def f(a,e,d,h):
...   print inspect.getargspec(f).args
...
>>> f(1,2,3,4)
['a', 'e', 'd', 'h']

Edit: without using the name of the function:

>>> def f(a,e,d,h):
...   print inspect.getargvalues(inspect.currentframe()).args
...
>>> f(1,2,3,4)
['a', 'e', 'd', 'h']

The function may looks like:

def validate_user(surname, username, passwd, password, errors):
    errors = []
    for arg in inspect.getargspec(validate_user).args[:-1]:
        value = eval(arg)
        if not value:
            errors.append("{0} may not be empty, please enter a {1}.".format(arg.capitalize(), arg))
        elif len(value) > 20:
            errors.append("Please shorten {0} to atmost 20 characters (|{1}|>20)".format(arg,value))
    return errors


>>> validate_user("foo","","mysuperlongpasswordwhichissecure","",[])
['Username may not be empty, please enter a username.', 'Please shorten passwd to atmost 20 characters (|mysuperlongpasswordwhichissecure|>20)', 'Password may not be empty, please enter a password.']

You can iterate over each argument by putting them in a list inside the function:

def validate(a,b,c):
    for item in [a,b,c]:
        print item

a=1
b=2
c=3

validate(a,b,c)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top