pratiks
3/28/2017 - 7:24 PM

Shorthand Notations

Shorthand Notations


#x = foo if condition else bar

self.HC_COOKIE = HC_COOKIE if HC_COOKIE is None else config['global']['HC_COOKIE']
self.CLOUD_ID = CLOUD_ID if CLOUD_ID is None else config['global']['CLOUD_ID']
self.FDOOR_HOST = FDOOR_HOST
"Retired" if var > 65 else "Working"
class RequestError(Exception):
    pass

def _try_page(url, attempt_number=1):
    max_attempts = 3
    try:
        response = requests.get(url)
        response.raise_for_status()
    except (requests.exceptions.RequestException, socket_error, S3ResponseError, BotoServerError) as e:
        if attempt_number < max_attempts:
            attempt = attempt_number + 1
            return _try_page(url, attempt_number=attempt)
        else:
            logger.error(e)
            raise RequestError('max retries exceed when trying to get the page at %s' % url)

    return response
# convert all k,v pairs in a list values to string 

conversations = dict((k, str(v)) for k,v in convert_response_to_string.iteritems())
from contextlib import ContextDecorator

class mycontext(ContextDecorator):
    def __enter__(self):
        print('Starting')
        return self

    def __exit__(self, *exc):
        print('Finishing')
        return False

>>> @mycontext()
... def function():
...     print('The bit in the middle')
...
>>> function()
Starting
The bit in the middle
Finishing

>>> with mycontext():
...     print('The bit in the middle')
...
Starting
The bit in the middle
Finishing