Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
namara-python / utils.py
Size: Mime:
from typing import TYPE_CHECKING, Callable
from collections import Mapping, Container
from sys import getsizeof

if TYPE_CHECKING:
    from urllib.request import Request

def gen_request_decorator(token:str) -> Callable[['Request'], 'Request']:
    def _request_decorator(request: 'Request') -> 'Request':
        ''' Takes in a `urllib.request.Request` and must return the same object
        '''

        request.add_header('Authorization', 'Bearer %s' % token)

        return request

    return _request_decorator


def to_camel_case(camel_str:str) -> str:
    components = camel_str.split('_')
    return ''.join([x.title() for x in components])

def listify(element):
    ''' Return element wrapped in a list. If its list already just return as is.
    '''
    if isinstance(element, list) or (element is None):
        return element
    else:
        return [element]

def deep_getsizeof(o, ids):
    """Find the memory footprint of a Python object
    This is a recursive function that rills down a Python object graph
    like a dictionary holding nested ditionaries with lists of lists
    and tuples and sets.
    The sys.getsizeof function does a shallow size of only. It counts each
    object inside a container as pointer only regardless of how big it
    really is.
    :param o: the object
    :param ids:
    :return:
    """
    d = deep_getsizeof
    if id(o) in ids:
        return 0

    r = getsizeof(o)
    ids.add(id(o))

    if isinstance(o, str):
        return r

    if isinstance(o, Mapping):
        return r + sum(d(k, ids) + d(v, ids) for k, v in o.items())

    if isinstance(o, Container):
        return r + sum(d(x, ids) for x in o)

    return r