0

I am writing a piece of software that checks the input to a function before passing it to a database. To do this I need to check the type of data before I send it. Right now I am using 5 different if/else statements. How can I condense this and make it easier to read? Thank You!

def addUser(USERNAME, PASSWORD, PHONE, CARRIER, SERVER): good = True if type(USERNAME) == str and good: good = True else: good = False if type(PASSWORD) == str and good: good = True else: good = False if type(PHONE) == int and good: good = True else: good = False if type(CARRIER) == str and good: good = True else: good = False if type(SERVER) == str and good: good = True else: good = False 
1
  • 3
    Probably worth noting that your 'addUser()' function probably shouldn't be responsible for validating the inputs. Whatever function gathers the inputs really should validate them before trying to pass them to 'addUser` Commented Dec 19, 2021 at 3:46

5 Answers 5

1

All the conditions must be True. The most pythonic way would be two create two lists — one with the fields and one with their respective types, then compare the two lists and check if all conditions are True. This way you can add any number of fields by appending the fields and types lists. This way you will also avoid one very long statement with multiple conditions and the and operator between them

fields = [USERNAME, PASSWORD, PHONE, CARRIER, SERVER] # append new field if you want types = [str, str, int, str, str] # append type of new field if you want good = all(type(field)==types[i] for i, field in enumerate(fields)) 
Sign up to request clarification or add additional context in comments.

Comments

0

Combine all the conditions into one:

good = type(USERNAME) == str and type(PASSWORD) == str and type(PHONE) == int AND type(CARRIER) == str and type(SERVER) == str 

BTW, you generally shouldn't use int for phone numbers. Even though we call them phone numbers we don't perform any numeric operations on them. And putting a phone number in an int variable will lose leading zeroes.

1 Comment

Ahh, Sorry! I am using postgres for the first time and I am still trying to figure out a system for storing things. I will definitely look in to that! Thanks
0

You could loop over all of them. e.g:

def check_parameters(params: list): for parameter in params: if not isinstance(parameter,str): return False return True def addUser(USERNAME, PASSWORD, PHONE, CARRIER, SERVER): good = check_parameters([USERNAME, PASSWORD, PHONE, CARRIER, SERVER]) 

Note isinstance(Your_string, str) is preferred to `type() == '

Comments

0

To build on JeffUK's answer, you should also raise an error to tell the user which one is wrong if one fails the type test ("Errors should never pass silently."):

def check_parameters(params: list): for i, parameter in enumerate(params): if not isinstance(parameter,str): raise ValueError(f'{parameter} in position {i} is {type(parameter)}, not string.') return True 

You then can wrap your function call in a try block to catch the error.

def addUser(USERNAME, PASSWORD, PHONE, CARRIER, SERVER): try: good = check_parameters([USERNAME, PASSWORD, PHONE, CARRIER, SERVER]) except ValueError as e: print(e) 

Comments

0

If you are using Python 3.10, a match-case statement might work well for your particular code.

You could also try putting the valid input types into a dictionary, which could condense the code by eliminating the else statements. e.g.,

data_type_check = {'username': str, 'password': str, 'phone': int, 'carrier': str, 'server': str} for var, key in zip([USERNAME, PASSWORD, PHONE, CARRIER, SERVER], ['username', 'password', 'phone', 'carrier', 'server']): good = type(var) == data_type_check[key] if not good: break 

or even simpler

for var, vartype in zip([USERNAME, PASSWORD, PHONE, CARRIER, SERVER], [str, str, int, str, str]): good = type(var) == vartype if not good: break 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.