Reputation: 1066
Given the following function:
def httpstatus(self, url, data=None, timeout=None):
if timeout is None:
timeout = socket._GLOBAL_DEFAULT_TIMEOUT
urlopen(url, data, timeout)
The timeout parameter should be optional. But if ommited I would like to use the socket._GLOBAL_DEFAULT_TIMEOUT value as shown in code. However, that one is a protected member. And that doesn't seems the right way. So different approach...
def httpstatus(self, url, data=None, timeout=None):
if timeout is None:
urlopen(url, data)
else:
urlopen(url, data, timeout)
Yack that one is even more dirty...
What is the right and proper way to fall back to the socket default timeout?
Upvotes: 2
Views: 116
Reputation: 22561
If you really dont want to use protected var, just take number from socket and comment from where you get it:
# settings
default_timeout = 100 # socket._GLOBAL_DEFAULT_TIMEOUT
another option is to use getattr
with default value:
default_timeout = getattr(socket, '_GLOBAL_DEFAULT_TIMEOUT', 100)
def httpstatus(self, url, data=None, timeout=default_timeout):
urlopen(url, data, timeout)
Upvotes: 1
Reputation: 13616
You can use the **
-syntax for that:
def httpstatus(self, url, data=None, timeout=None):
kwargs = {}
if timeout is not None:
kwargs['timeout'] = timeout
urlopen(url, data, **kwargs)
Or even:
def httpstatus(self, url, data=None, **kwargs):
# Don't forget to mention in documentation that all
# extra arguments are passed to urlopen as is.
urlopen(url, data, **kwargs)
Upvotes: 1