Python: how to check if an extra argument can be used?

With urllib2, recent versions allow the optional "context" parameter to be used when calling urlopen.

I put together some code to use it:

# For Python 3.0 and later
from urllib.request import urlopen, HTTPError, URLError
except ImportError:
# Fall back to Python 2 urllib2
from urllib2 import urlopen, HTTPError, URLError
import ssl

context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
response = urlopen(url=url, context=context)

      

Running this with my python 2.78 ... I get:

Traceback (most recent call last):
  File "test.py", line 5, in <module>
  context = ssl.create_default_context()
  AttributeError: 'module' object has no attribute 'create_default_context'

      

So I thought: then let's move on to python3; and now i get:

Traceback (most recent call last):
  File "test.py", line 15, in <module>
    response = urlopen(url=url, context=context)
TypeError: urlopen() got an unexpected keyword argument 'context'

      

It took me a while to figure out that using this context with a named argument ... also requires a newer version of python than 3.4.0 installed on my ubuntu 14.04.

My question is, what is the "canonical" way to check if the "context" can be used when calling urlopen? Just call and expect a TypeError? Or do an exact version check on the python I'm running in?

I searched here and using google, but maybe I just missed the correct search term ... as I couldn't find anything useful ...

+3


source to share


3 answers


How can I check the signature of the function here: How can I read the signature of the function including the default argument values?

However, some functions have common signatures such as:



def myfunc(**kwargs):
    print kwargs.items()

    if kwargs.has_key('foo'):
        ...

    if kwargs.has_key('bar'):
        ...

      

for which it is impossible to know what arguments they are using before calling them. For example, matplotlib

/ pylab

has many such functions using kwargs

.

+2


source


Use try / except. See python glossary :

ESPC



It's easier to ask for forgiveness than permission. This general Python coding style assumes that there are valid keys or attributes and throws exceptions if the assumption turns out to be false. This clean and fast style is characterized by many attempts and exceptions. This technique contrasts with the LBYL standard common to many other languages ​​such as C.

+2


source


Check Python version:

import sys

if sys.hexversion >= 0x03050000:
    urlopen = urllib.urlopen
else:
    def urlopen (*args, context=None, **kwargs):
        return urllib.urlopen(*args, **kwargs)

      

Now just use urlopen()

instead urllib.urlopen()

.

This will break in early alphas 3.5, I think, but alphas should break, so I don't care about tracking down the exact version in which this argument was introduced.

+1


source







All Articles