def with_ctx(func=None):
    ''' Auto create a new context if not available '''
    if not func:
        return functools.partial(with_ctx)

    @functools.wraps(func)
    def func_with_context(_obj, *args, **kwargs):
        if 'ctx' not in kwargs or kwargs['ctx'] is None:
            # if context is empty, ensure context
            with _obj.ctx() as new_ctx:
                kwargs['ctx'] = new_ctx
                return func(_obj, *args, **kwargs)
        else:
            # if context is available, just call the function
            return func(_obj, *args, **kwargs)

    return func_with_context
def with_ctx ( func = None ) : if not func : return functools . partial ( with_ctx ) @ functools . wraps ( func ) def func_with_context ( _obj , * args , ** kwargs ) : if 'ctx' not in kwargs or kwargs [ 'ctx' ] is None : with _obj . ctx ( ) as new_ctx : kwargs [ 'ctx' ] = new_ctx return func ( _obj , * args , ** kwargs ) else : return func ( _obj , * args , ** kwargs ) return func_with_context
Auto create a new context if not available