How to ensure that the input of a function is within a list of options?

36 Views Asked by At

I want to define a list of possible inputs to a function, similar to an enum. The application is for http requests, and I want to create a wrapper for requests to handle the errors. The wrapper will need a request type parameter, get, put, delete, etc. What is the best way to ensure that the request type is a legal input?

This is the code I've already tried. The response is

request type: request_type_library.request_type Uknown request type. Defaulted to get. Valid Request types: {<request_type_library.request_type: 1>: ['GET', 'PUT', 'DELETE']}

import requests
from enum import Enum, auto

class RequestTypeLibrary(Enum):
    request_type = auto()

request_type_dictionary = {RequestTypeLibrary.request_type: ["GET","PUT","DELETE"]}

class RequestTypeLoader:
    def __init__(self, request_type: RequestTypeLibrary):
        self.request_type = request_type

    def load_request_type(self):
        print(f"loaded request type: {request_type_dictionary[self.request_type]}")

def request_wrapper(request_type: RequestTypeLibrary,url,timeout=10):
    print("request type:", request_type)
    if request_type=="GET":
        r= requests.get(url,timeout=timeout)
    elif request_type=="PUT":
        r= requests.put(url,timeout=timeout)
    elif request_type=="DELETE":
        r= requests.delete(url,timeout=timeout)
    else:
        r= requests.get(url,timeout=timeout)
        print("Uknown request type. Defaulted to get. Valid Request types: ", request_type_dictionary)
    return r

r = request_wrapper(request_type=RequestTypeLibrary.request_type,url=url,timeout=10,)
1

There are 1 best solutions below

0
KamilCuk On

What is the best way to ensure that the request type is a legal input?

So create the enum states.

import enum
class RequestType(enum.StrEnum):
  GET = enum.auto()
  POST = enum.auto()
  PUT = enum.auto()
  DELETE = enum.auto()

You could assert that the value is sane. Something along, untested.

def request_wrapper(request_type: RequestType, ...):
     assert isinstance(request_type, RequestType)