def test_getsource():
  assert getsource(f) == 'f = lambda x: x**2\n'
  assert getsource(g) == 'def g(x): return f(x) - x\n'
  assert getsource(h) == 'def h(x):\n  def g(x): return x\n  return g(x) - x\n'
  assert getname(f) == 'f'
  assert getname(g) == 'g'
  assert getname(h) == 'h'
  assert _wrap(f)(4) == 16
  assert _wrap(g)(4) == 12
  assert _wrap(h)(4) == 0

  assert getname(Foo) == 'Foo'
  assert getname(Bar) == 'Bar'
  assert getsource(Bar) == 'class Bar:\n  pass\n'
  assert getsource(Foo) == 'class Foo(object):\n  def bar(self, x):\n    return x*x+x\n'
Esempio n. 2
0
def compare(func, list_to_sort):
    if func == sorts.pancake_sort or func == sorts.tree_sort:
        start_time = timeit.default_timer()
        func(list_to_sort)
        print(getname(func), "Result: ",
              timeit.default_timer() - start_time, "s")
    elif func == sorts.quick_sort:
        start_time = timeit.default_timer()
        func(list_to_sort, 0, len(list_to_sort) - 1)
        print(getname(func), "Result: ",
              timeit.default_timer() - start_time, "s")
    else:
        start_time = timeit.default_timer()
        func(list_to_sort, 0, len(list_to_sort))
        print(getname(func), "Result: ",
              timeit.default_timer() - start_time, "s")
Esempio n. 3
0
def run_source(obj):
    _obj = source._wrap(obj)
    assert _obj(1.57) == obj(1.57)
    src = source.getimportable(obj, alias='_f')
    exec(src, globals())
    assert _f(1.57) == obj(1.57)
    name = source.getname(obj)
    assert name == obj.__name__ or src.split("=",1)[0].strip()
Esempio n. 4
0
def test_source(obj):
    _obj = source._wrap(obj)
    assert _obj(1.57) == obj(1.57)
    src = source.importable(obj, alias='_f')
    exec src in globals(), locals()
    assert _f(1.57) == obj(1.57)
    name = source.getname(obj)
    assert name == obj.__name__ or src.split("=", 1)[0].strip()
Esempio n. 5
0
 def __dumpsfunc(self, funcs, modules):
     """Serializes functions and modules"""
     hashs = hash(funcs + modules)
     if hashs not in self.__sfuncHM:
         sources = [self.__get_source(func) for func in funcs]
         self.__sfuncHM[hashs] = pickle.dumps(
             (getname(funcs[0]), sources, modules), self.__pickle_proto)
     return self.__sfuncHM[hashs]
Esempio n. 6
0
 def __dumpsfunc(self, funcs, modules):
     """Serializes functions and modules"""
     hashs = hash(funcs + modules)
     if hashs not in self.__sfuncHM:
         sources = [self.__get_source(func) for func in funcs]
         # should probably just 'try' above, if fail rely on dill.dumps
         self.__sfuncHM[hashs] = pickle.dumps(
             (getname(funcs[0]), sources, modules), self.__pickle_proto)
     return self.__sfuncHM[hashs]
Esempio n. 7
0
def run_source(obj):
    _obj = source._wrap(obj)
    assert _obj(1.57) == obj(1.57)
    src = source.importable(obj, alias='_f')
    # LEEK: for 3.x, locals may not be modified
    # (see https://docs.python.org/3.6/library/functions.html#locals)
    #
    my_locals = locals()
    exec(src, globals(), my_locals)
    assert my_locals["_f"](1.57) == obj(1.57)
    name = source.getname(obj)
    assert name == obj.__name__ or src.split("=", 1)[0].strip()
Esempio n. 8
0
    def submit(self,
               func,
               args=(),
               depfuncs=(),
               modules=(),
               callback=None,
               callbackargs=(),
               group='default',
               globals=None):
        """Submits function to the execution queue

            func - function to be executed
            args - tuple with arguments of the 'func'
            depfuncs - tuple with functions which might be called from 'func'
            modules - tuple with module names to import
            callback - callback function which will be called with argument \
                    list equal to callbackargs+(result,) \
                    as soon as calculation is done
            callbackargs - additional arguments for callback function
            group - job group, is used when wait(group) is called to wait for
            jobs in a given group to finish
            globals - dict from which all modules, functions, and classes \
                    will be imported, for instance: globals=globals()
        """

        # perform some checks for frequent mistakes
        if self._exiting:
            raise DestroyedServerError("Cannot submit jobs: server"\
                    " instance has been destroyed")

        if not isinstance(args, tuple):
            raise TypeError("args argument must be a tuple")

        if not isinstance(depfuncs, tuple):
            raise TypeError("depfuncs argument must be a tuple")

        if not isinstance(modules, tuple):
            raise TypeError("modules argument must be a tuple")

        if not isinstance(callbackargs, tuple):
            raise TypeError("callbackargs argument must be a tuple")

        if globals is not None and not isinstance(globals, dict):
            raise TypeError("globals argument must be a dictionary")

        for module in modules:
            if not isinstance(module, str):
                raise TypeError("modules argument must be a list of strings")

        tid = self.__gentid()

        other_type = types.FunctionType if six.PY3 else types.ClassType
        if globals:
            modules += tuple(self.__find_modules("", globals))
            modules = tuple(set(modules))
            self.logger.debug("Task %i will autoimport next modules: %s" %
                              (tid, str(modules)))
            for object1 in globals.values():
                if isinstance(object1, types.FunctionType) \
                        or isinstance(object1, other_type):
                    depfuncs += (object1, )

        task = _Task(self, tid, callback, callbackargs, group)

        self.__waittasks_lock.acquire()
        self.__waittasks.append(task)
        self.__waittasks_lock.release()

        # if the function is a method of a class add self to the arguments list
        if isinstance(func, types.MethodType):
            func_self = func.__self__ if six.PY3 else func.im_self
            if func_self is not None:
                args = (func_self, ) + args

        # if there is an instance of a user defined class in the arguments add
        # whole class to dependancies
        for arg in args:
            # Checks for both classic or new class instances
            if (six.PY2 and isinstance(arg, types.InstanceType)) \
                        or str(type(arg))[:6] == "<class":
                # in PY3, all instances are <class... so skip the builtins
                if getattr(inspect.getmodule(arg), '__name__', None) \
                   in ['builtins', '__builtin__', None]:
                    pass
                    # do not include source for imported modules
                elif ppc.is_not_imported(arg, modules):
                    depfuncs += tuple(ppc.get_class_hierarchy(arg.__class__))

        # if there is a function in the arguments add this
        # function to dependancies
        for arg in args:
            if isinstance(arg, types.FunctionType):
                depfuncs += (arg, )

        sfunc = self.__dumpsfunc((func, ) + depfuncs, modules)
        sargs = pickle.dumps(args, self.__pickle_proto)

        self.__queue_lock.acquire()
        self.__queue.append((task, sfunc, sargs))
        self.__queue_lock.release()

        self.logger.debug("Task %i submited, function='%s'" %
                          (tid, getname(func)))
        self.__scheduler()
        return task
Esempio n. 9
0
# yes, same as 'f', but things are tricky when it comes to pointers
squared = lambda x: x**2


class Bar:
    pass


_bar = Bar()

# inspect.getsourcelines # dill.source.getblocks
assert getsource(f) == 'f = lambda x: x**2\n'
assert getsource(g) == 'def g(x): return f(x) - x\n'
assert getsource(h) == 'def h(x):\n  def g(x): return x\n  return g(x) - x \n'
assert getname(f) == 'f'
assert getname(g) == 'g'
assert getname(h) == 'h'
assert _wrap(f)(4) == 16
assert _wrap(g)(4) == 12
assert _wrap(h)(4) == 0

assert getname(Foo) == 'Foo'
assert getname(Bar) == 'Bar'
assert getsource(Bar) == 'class Bar:\n  pass\n'
assert getsource(
    Foo) == 'class Foo(object):\n  def bar(self, x):\n    return x*x+x\n'
#XXX: add getsource for  _foo, _bar

assert getimportable(add) == 'from %s import add\n' % __name__
assert getimportable(squared) == 'from %s import squared\n' % __name__
def save_model(model):
    model_name = getname(model)
    print(f"Saving model as model/{model_name}.pkl")