Skip to content

Instantly share code, notes, and snippets.

@ArunVenkata
Last active September 20, 2022 06:26
Show Gist options
  • Save ArunVenkata/9e9441bb379eb5bce084d270a8441bcf to your computer and use it in GitHub Desktop.
Save ArunVenkata/9e9441bb379eb5bce084d270a8441bcf to your computer and use it in GitHub Desktop.
Useful python snippets

Note: Modify and use as needed. Suggestions for improvements are welcome!

Parameter validator - useful to validate parameters for any api/function etc.

""" Usage:
from uuid import UUID
print(check_mandatory_params(
    {"score": 7.5, "id": "e76cbfa0-06e6-4ad9-8209-3ae786cf344d", "name": "John" },
    [
        ("score", float),
        ("id", UUID),
        ("name", str),
        ("status", lambda x: x in ["resolved", "pending"], False, "Status needs to be one of 'resolved', 'pending'"),
        ("age", lambda item: isinstance(item, int) and item >= 18, False, "Applicant must be of legal age")
    ],
))

>> {"success": True}

print(check_mandatory_params(
    {"id": "e76cbfa0-06e6-4ad9-8209-3ae786cf344d", "name": "John" },
    [
        ("score", float, True),
        ("id", UUID),
        ("name", str),
        ("status", lambda x: x in ["resolved", "pending"], False, "Status needs to be one of 'resolved', 'pending'"),
        ("age", lambda item: isinstance(item, int) and item >= 18, False, "Applicant must be of legal age")
    ]
))

>> {'success': False, 'message': 'score is missing'}
"""
def check_mandatory_params(
    params: dict, mandatory_attributes: "list[any, type]" = []
) -> dict:
    
    for attr in mandatory_attributes:
        is_mandatory = True
        try:
            attr_name, attr_type, *remaining = attr
            
            is_mandatory = remaining[0] if remaining and remaining[0] in [True, False] else True
            error_msg = remaining[1] if remaining[1:] else None

            
            if is_mandatory and (attr_name not in params):
                return {"success": False, "message": f"{attr_name} is missing"}
            elif callable(attr_type) and attr_type.__name__ == "<lambda>":
                if is_mandatory and params.get(attr_name) is None:
                    return {"success": False, "message": f"{attr_name} is missing"}
                if is_mandatory and not attr_type(params.get(attr_name)):
                    if error_msg:
                        return {"success": False, "message": error_msg}
                    return {
                        "success": False,
                        "message": f"Invalid Data format for '{attr_name}'",
                    }
            elif not isinstance(params.get(attr_name), attr_type):
                try:
                    if isinstance(attr_type(params.get(attr_name)), attr_type):
                        continue
                except:
                    if error_msg:
                        return {"success": False, "message": error_msg}
                    return {
                        "success": False,
                        "message": f"{attr_name} is not of type {attr_type.__name__}",
                    }
                return {
                    "success": False,
                    "message": f"{attr_name} is of incorrect type",
                }
            continue
        except:
            pass
        if attr not in params:
            return {"success": False, "message": f"{attr_name} is missing"}
    return {"success": True}

UUID Validator

import uuid
def is_valid_uuid(value):
    try:
        uuid.UUID(str(value))
        return True
    except Exception:
        return False

Check for presence of nested attributes using . object notation

def dotsplitgen(string):
    """    
    generator version of str.split(".")
    """
    buffer = ""
    for character in string:
        if character == ".":
            temp_buff = buffer + ""
            buffer = ""
            if temp_buff == "":
                continue
            yield temp_buff
            continue
        buffer+=character
    else:
        if buffer!="":
            yield buffer
    
    


def hasattr_nested(obj, path):
    """
    Check presence of nested attributes
    """
    for item in dotsplitgen(path):
        if hasattr(obj, item):
            obj = getattr(obj, item, None)
        else:
            break
    else:
        return True

    return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment