Call function via literal name

Jon Ribbens jon+usenet at unequivocal.eu
Fri Jul 29 16:58:52 EDT 2016


On 2016-07-29, TUA <kai.peters at gmail.com> wrote:
> Rather than do this:
>
>         if test['method'] == 'GET':
>                 res = requests.get(test['endpoint'],    auth=test['auth'], verify=False)        
>         elif test['method'] == 'POST':
>                 res = requests.post(test['endpoint'],   auth=test['auth'], verify=False, json=test['body'])        
>         elif test['method'] == 'PUT':
>                 res = requests.put(test['endpoint'],    auth=test['auth'], verify=False, json=test['body'])        
>         elif test['method'] == 'DELETE':
>                 res = requests.delete(test['endpoint'], auth=test['auth'], verify=False)        
>         elif test['method'] == 'HEAD':
>                 res = requests.head(test['endpoint'],   auth=test['auth'], verify=False)  
>
> I would like to call the requests method that corresponds to
> test['method'] by finding that function by name - how can I achieve
> that?

    if test['method'] not in ('GET', 'POST', 'PUT', 'DELETE', 'HEAD'):
        raise ValueError('Unknown method %r' % (test['method'],))

    res = getattr(requests, test['method'].lower())(
        test['endpoint'], auth=test['auth'], verify=False)

although in the specific case of using requests you could just do:

    res = requests.request(test['method'], test['endpoint'],
                           auth=test['auth'], verify=False)



More information about the Python-list mailing list