Yes — you can build a multipurpose error-handling function in Python that ensures the input matches one of several expected formats (like list of numbers, single number, string, dict, tuple), and returns appropriate errors if not.


✅ Goal

a robust validator function that:

  • Accepts an input string (as from input() or a user-facing API).
  • Tries to interpret it as:
    • A list of numbers (comma- or space-separated)
    • A number (int/float)
    • A string
    • A dictionary
    • A tuple
  • Returns a parsed object or custom error if format is wrong.

✅ Sample Implementation

import ast

def parse_user_input(user_input: str):
    # Strip whitespace
    user_input = user_input.strip()

    # Check if it's a list of numbers (comma or space separated)
    if ',' in user_input or ' ' in user_input:
        parts = [p.strip() for p in user_input.replace(',', ' ').split()]
        try:
            numbers = [float(x) if '.' in x else int(x) for x in parts]
            return {'type': 'list_of_numbers', 'value': numbers}
        except ValueError:
            return {'error': 'Invalid list of numbers. Use digits separated by space or comma.'}
    
    # Try to parse using ast.literal_eval safely
    try:
        evaluated = ast.literal_eval(user_input)
        if isinstance(evaluated, (int, float)):
            return {'type': 'number', 'value': evaluated}
        elif isinstance(evaluated, str):
            return {'type': 'string', 'value': evaluated}
        elif isinstance(evaluated, dict):
            return {'type': 'dict', 'value': evaluated}
        elif isinstance(evaluated, tuple):
            return {'type': 'tuple', 'value': evaluated}
        elif isinstance(evaluated, list):
            return {'error': 'Lists must contain only numbers, separated by comma or space.'}
        else:
            return {'error': f'Unsupported data type: {type(evaluated).__name__}'}
    except Exception:
        return {'error': 'Invalid input format. Could not parse.'}

🧪 Example Usage

examples = [
    "1, 2, 3",
    "4 5 6",
    "42",
    "'hello world'",
    "{'name': 'Raj', 'age': 30}",
    "(1, 2, 3)",
    "[1, 'two']",
    "{1, 2, 3}"  # set
]

for e in examples:
    print(f"Input: {e}")
    print("Result:", parse_user_input(e))
    print("---")

📌 Output

Input: 1, 2, 3
Result: {'type': 'list_of_numbers', 'value': [1, 2, 3]}

Input: 4 5 6
Result: {'type': 'list_of_numbers', 'value': [4, 5, 6]}

Input: 42
Result: {'type': 'number', 'value': 42}

Input: 'hello world'
Result: {'type': 'string', 'value': 'hello world'}

Input: {'name': 'Raj', 'age': 30}
Result: {'type': 'dict', 'value': {'name': 'Raj', 'age': 30}}

Input: (1, 2, 3)
Result: {'type': 'tuple', 'value': (1, 2, 3)}

Input: [1, 'two']
Result: {'error': 'Lists must contain only numbers, separated by comma or space.'}

Input: {1, 2, 3}
Result: {'error': 'Unsupported data type: set'}

def parse_user_input(user_input: str):
    user_input = user_input.strip()

    # Remove outer brackets if any
    if user_input.startswith("[") and user_input.endswith("]"):
        user_input = user_input[1:-1].strip()

    # Normalize commas and spaces → replace commas with space first
    normalized = user_input.replace(',', ' ')
    parts = normalized.split(' ')

    result = []
    for x in parts:
        if x == '':
            result.append(None)
        else:
            try:
                num = int(float(x))
                if num < 0:
                    return {'error': 'Only positive integers and nulls allowed.'}
                result.append(num)
            except ValueError:
                return {'error': f'Invalid entry "{x}". Only integers and nulls allowed.'}

    return {'type': 'list_of_positive_integers_with_nulls', 'value': result}
parse_user_input(input("Enter List of Positive Integer")) 
def parse_user_input(user_input: str, allow_zero: bool = False):
    user_input = user_input.strip()

    # Remove outer brackets if any
    if user_input.startswith("[") and user_input.endswith("]"):
        user_input = user_input[1:-1].strip()

    # Normalize commas to spaces
    normalized = user_input.replace(',', ' ')
    parts = normalized.split()  # This removes multiple spaces and empties

    result = []
    metadata = []

    for idx, x in enumerate(normalized.split(' ')):  # Preserve empty entries for null tracking
        x = x.strip()
        if x == '':
            result.append(None)
            metadata.append({
                'index': idx,
                'input': '',
                'type': 'null',
                'status': 'OK'
            })
        else:
            try:
                num = int(float(x))
                if num < 0:
                    return {
                        'error': f'Negative number "{x}" at position {idx}',
                        'position': idx
                    }
                if not allow_zero and num == 0:
                    return {
                        'error': f'Zero not allowed at position {idx}',
                        'position': idx
                    }
                result.append(num)
                metadata.append({
                    'index': idx,
                    'input': x,
                    'type': 'integer',
                    'status': 'OK'
                })
            except ValueError:
                return {
                    'error': f'Invalid number "{x}" at position {idx}',
                    'position': idx
                }

    return {
        'type': 'list_of_positive_integers_with_nulls',
        'value': result,
        'metadata': metadata
    }

Pages: 1 2


Discover more from HintsToday

Subscribe to get the latest posts sent to your email.

Posted in

Leave a Reply

Your email address will not be published. Required fields are marked *

Discover more from HintsToday

Subscribe now to keep reading and get access to the full archive.

Continue reading