Baz
Baz

Reputation: 13123

Avoid having to explicitly include a function parameter

My code looks something like this:

import requests
s = requests.Session()
r = s.get(a, verify=False)
r = s.get(b, verify=False)
r = s.get(c, verify=False)
r = s.get(d, verify=False)
r = s.get(e, verify=False)
r = s.get(f, verify=False)
r = s.get(g, headers={"a":"b"}, verify=False)
r = s.post(h, data={"a","b"},verify=False)

How can I avoid having to explicitly write verify=False all the time?

Upvotes: 3

Views: 81

Answers (2)

e4c5
e4c5

Reputation: 53734

In the case of python requests, you can make the SSL verify flag last the lifetime of that session by doing

s.verify = False

More generally when a function accepts named=value type parameters the first thing to do is to inspect the method signature to see if the default value is perhaps what you want it to be. If it isn't the next thing is to see if the value be persisted as above (which python requests allows to do).

The third option is to create a simple wrapper which passes suitable values for all parameters

def my_get(s, url):
    s.get(url, verify=False)

called as

my_get(s, url)

Or you can get really ambitious and monkey patch the class from the library. But monkey patching can sometimes lead to unexpected side effects so it's best avoided unless as a very last resort.

References:
the documentation for the verify attribute of the Session class.
Using Optional and named arguments.

Upvotes: 7

Azat Ibrakov
Azat Ibrakov

Reputation: 10963

easily can be done using partial

get_unverified = partial(s.get, verify=False)
post_unverified = partial(s.post, verify=False)
r = get_unverified(a)
r = get_unverified(b)
r = get_unverified(c)
r = get_unverified(d)
r = get_unverified(e)
r = get_unverified(f)
r = get_unverified(g, headers={"a":"b"})
r = post_unverified(h, data={"a","b"})

Upvotes: 4

Related Questions