diff --git a/modules/packages/Python.chpl b/modules/packages/Python.chpl index 52c871e5ce4a..f20be2864959 100644 --- a/modules/packages/Python.chpl +++ b/modules/packages/Python.chpl @@ -53,7 +53,7 @@ .. warning:: - Chapel programs compiled in this was are compiled for a specific Python + Chapel programs compiled in this way are compiled for a specific Python version. Attempting to run the compiled program with a different Python version may have unexpected results. @@ -116,8 +116,8 @@ var interpreter = new Interpreter(); coforall 0..#4 { var subInterpreter = new SubInterpreter(interpreter); - var m = new Module(subInterpreter, 'myMod', code); - var hello = new Function(m, 'hello'); + var m = subInterpreter.importModule('myMod', code); + var hello = m.get('hello'); hello(); } } @@ -149,7 +149,7 @@ proc init(parent: borrowed Interpreter, code: string) { init this; i = try! (new SubInterpreter(parent)); - m = try! (new Module(i!, "anon", code)); + m = try! (i!.importModule("anon", code)); } } @@ -158,7 +158,7 @@ forall i in 1..10 with (var mod = new perTaskModule(interpreter, "x = 10")) { - writeln(mod.m!.getAttr(int, "x")); + writeln(mod.m!.get(int, "x")); } } @@ -192,7 +192,7 @@ var Arr: [1..10] int = 1..10; var interp = new Interpreter(); - var func = new Function(interp, "lambda x,: x * x"); + var func = interp.compileLambda("lambda x,: x * x"); var ts = new threadState(); ts.save(); // save the thread state @@ -224,7 +224,7 @@ var Arr: [1..10] int = 1..10; var interp = new Interpreter(); - var func = new Function(interp, "lambda x,: x * x"); + var func = interp.compileLambda("lambda x,: x * x"); var ts = new threadState(); ts.save(); // save the thread state @@ -270,7 +270,7 @@ on l { // each locale has its own interpreter const interp = new Interpreter(); - const func = new Function(interp, "lambda x,: x + 1"); + const func = interp.compileLambda("lambda x,: x + 1"); var ts = new threadState(); ts.save(); @@ -319,7 +319,7 @@ use Python, IO; var interp = new Interpreter(); - var func = new Function(interp, "lambda x,: print(x)"); + var func = interp.compileLambda("lambda x,: print(x)"); writeln("Hello from Chapel"); writeln("Let's call some Python!"); @@ -509,7 +509,7 @@ module Python { if pyMemLeaks { // import objgraph - this.objgraph = this.importModule("objgraph"); + this.objgraph = this.importModuleInternal("objgraph"); if this.objgraph == nil { writeln("objgraph not found, memory leak detection disabled. " + "Install objgraph with 'pip install objgraph'"); @@ -555,6 +555,67 @@ module Python { Py_Finalize(); } + + /* + Import a Python module. This is equivalent to calling ``import modName`` + in Python. + + .. warning:: + + Importing a second module with the same name will overwrite the first. + + :arg modName: The name of the module that will be created. Note that if + the module name already exists, it will be replaced. + */ + proc importModule(modName: string): owned Module throws { + return new Module(this, modName); + } + /* + Import a Python module, using the provided ``moduleContents``. This is + equivalent to putting the code in a file, and then importing the file + via the file/module name. + + .. warning:: + + Importing a second module with the same name will overwrite the first. + + :arg modName: The name of the module that will be created. Note that if + the module name already exists, it will be replaced. + :arg moduleContents: The contents of the module. This can be a + :type:`~String.string` of Python code or a + :type:`~Bytes.bytes` object containing Python + bytecode (i.e. from a ``*.pyc`` file). + */ + proc importModule(modName: string, moduleContents): owned Module throws + where moduleContents.type == string || moduleContents.type == bytes { + return new Module(this, modName, moduleContents); + } + + /* + Load a `Python Pickle `_ + as a Python object. + + :arg pickle: The pickle data to load + */ + proc load(pickle: bytes): owned Value throws { + return new Value(this, pickle); + } + + /* + Compile a lambda function like 'lambda x,: x + 1' + + Note: this only works with lambdas that accept a tuple of arguments, + like 'x,' or '\*args' + + For example: + .. code-block:: chapel + + interpreter.compileLambda("lambda x, y,: x + y"); + */ + proc compileLambda(code: string): owned Function throws { + return new Function(this, code); + } + /* Run a string of python code. @@ -582,12 +643,12 @@ module Python { Compile a lambda function like 'lambda x,: x + 1' Note: this only works with lambdas that accept a tuple of arguments, - like 'x,' or '*args' + like 'x,' or '\*args' Creates a new reference */ @chpldoc.nodoc - proc compileLambda(l: string): PyObjectPtr throws { + proc compileLambdaInternal(l: string): PyObjectPtr throws { var globals = chpl_PyEval_GetFrameGlobals(); var globalsNeedDecref = false; // create a globals if it doesn't exist @@ -607,15 +668,12 @@ module Python { } /* - Compile a chunk of python code as a module and return the module object. - - This is equivalent to running the code in a file, and then importing the - module. + Compile a chunk of Python code as a module and return the module object. Creates a new reference */ @chpldoc.nodoc - proc compileModule(s: string, modname: string = "chplmod"): PyObjectPtr throws + proc compileModule(s: string, modname: string): PyObjectPtr throws { var code = Py_CompileString(s.c_str(), "", Py_file_input); this.checkException(); @@ -630,15 +688,10 @@ module Python { Interpret a chunk of Python bytecode as a Python module and return the module object. - This is equivalent to running the code in a file, and then importing the - module. However, this takes the bytecode directly (i.e. *.pyc files), - rather than the source. - Creates a new reference */ @chpldoc.nodoc - proc compileModule(b: bytes, - modname: string = "chplmod"): PyObjectPtr throws { + proc compileModule(b: bytes, modname: string): PyObjectPtr throws { var code = PyMarshal_ReadObjectFromString(b.c_str(), b.size.safeCast(Py_ssize_t)); this.checkException(); @@ -656,7 +709,7 @@ module Python { */ @chpldoc.nodoc proc loadPickle(b: bytes): PyObjectPtr throws { - var pickle = importModule("pickle"); + var pickle = importModuleInternal("pickle"); this.checkException(); defer Py_DECREF(pickle); var loads = PyObject_GetAttrString(pickle, "loads"); @@ -682,7 +735,7 @@ module Python { // the first 4 bytes are the magic number // we validate it against 'importlib.util.MAGIC_NUMBER' var magic = header[0..#4]; - var importlib_util = importModule("importlib.util"); + var importlib_util = importModuleInternal("importlib.util"); this.checkException(); defer Py_DECREF(importlib_util); var MAGIC_NUMBER_py = @@ -742,7 +795,7 @@ module Python { } @chpldoc.nodoc - inline proc importModule(in modName: string): PyObjectPtr throws { + inline proc importModuleInternal(in modName: string): PyObjectPtr throws { var mod = PyImport_ImportModule(modName.c_str()); try { this.checkException(); @@ -805,8 +858,8 @@ module Python { } else if isSubtype(t, List.list) { return toList(val); } else if isSubtype(t, Value) { - Py_INCREF(val.get()); - return val.get(); + Py_INCREF(val.getPyObject()); + return val.getPyObject(); } else if t == NoneType { return Py_None; } else { @@ -1265,6 +1318,7 @@ module Python { /* Creates a new Python object from a pickle. + See :proc:`Interpreter.load`. :arg interpreter: The interpreter that this object is associated with. :arg pickleData: The pickle data to load. @@ -1299,50 +1353,14 @@ module Python { Py_DECREF(this.obj); } - inline proc check() throws do this.interpreter.checkException(); - /* - Returns the :type:`~CTypes.c_ptr` to the underlying Python object. - */ - proc get() do return this.obj; + Check if an exception has occurred in the interpreter. - /* - Returns the Chapel value of the object. + ``val.check();`` is equivalent to ``val.interpreter.checkException();`` - This is a shortcut for calling :proc:`~Interpreter.fromPython` on this - object, however it does not consume the object. + See :proc:`~Interpreter.checkException` for more information. */ - proc value(type value) throws { - // fromPython will decrement the reference count, so we need to increment it - Py_INCREF(this.obj); - return interpreter.fromPython(value, this.obj); - } - - /* - Stop owning val, return the underlying ptr. - */ - proc type release(in val: owned Value): PyObjectPtr { - var valUn: unmanaged = owned.release(val); - valUn.isOwned = false; - var ptr: PyObjectPtr = valUn.obj; - delete valUn; - return ptr; - } - /* - Create a new Value, taking ownership of the object. - */ - proc type adopting(in interpreter: borrowed Interpreter, in ptr: PyObjectPtr): owned Value throws { - var val = new Value(interpreter, ptr, isOwned=true); - return val; - } - /* - Create a new Value, borrowing the object. - */ - proc type borrowing(in interpreter: borrowed Interpreter, in ptr: PyObjectPtr): owned Value throws { - var val = new Value(interpreter, ptr, isOwned=false); - return val; - } - + inline proc check() throws do this.interpreter.checkException(); /* Returns the string representation of the object. @@ -1389,7 +1407,7 @@ module Python { where kwargs.isAssociative() { var pyArg = this.packTuple((...args)); defer Py_DECREF(pyArg); - return callInternal(retType, pyArg, kwargs); + return callInternal(retType, this.getPyObject(), pyArg, kwargs); } pragma "last resort" @chpldoc.nodoc @@ -1398,7 +1416,7 @@ module Python { where kwargs.isAssociative() { var pyArg = this.packTuple((...args)); defer Py_DECREF(pyArg); - return callInternal(owned Value, pyArg, kwargs); + return callInternal(owned Value, this.getPyObject(), pyArg, kwargs); } pragma "last resort" @chpldoc.nodoc @@ -1406,28 +1424,28 @@ module Python { kwargs:?=none): retType throws where kwargs.isAssociative() { var pyArgs = Py_BuildValue("()"); defer Py_DECREF(pyArgs); - return callInternal(retType, pyArgs, kwargs); + return callInternal(retType, this.getPyObject(), pyArgs, kwargs); } pragma "last resort" @chpldoc.nodoc proc this(kwargs:?=none): owned Value throws where kwargs.isAssociative() { var pyArgs = Py_BuildValue("()"); defer Py_DECREF(pyArgs); - return callInternal(owned Value, pyArgs, kwargs); + return callInternal(owned Value, this.getPyObject(), pyArgs, kwargs); } @chpldoc.nodoc proc this(type retType, const args...): retType throws { var pyArg = this.packTuple((...args)); defer Py_DECREF(pyArg); - return callInternal(retType, pyArg, none); + return callInternal(retType, this.getPyObject(), pyArg, none); } @chpldoc.nodoc proc this(const args...): owned Value throws do return this(owned Value, (...args)); @chpldoc.nodoc proc this(type retType = owned Value): retType throws { - var pyRes = PyObject_CallNoArgs(this.get()); + var pyRes = PyObject_CallNoArgs(this.getPyObject()); this.check(); var res = interpreter.fromPython(retType, pyRes); @@ -1449,12 +1467,14 @@ module Python { } @chpldoc.nodoc proc callInternal(type retType, - pyArg: PyObjectPtr, kwargs: ?t): retType throws { + pyFunc: PyObjectPtr, + pyArg: PyObjectPtr, + kwargs: ?t): retType throws { var pyKwargs; if t != nothing then pyKwargs = interpreter.toPython(kwargs); else pyKwargs = nil; - var pyRes = PyObject_Call(this.obj, pyArg, pyKwargs); + var pyRes = PyObject_Call(pyFunc, pyArg, pyKwargs); this.check(); var res = interpreter.fromPython(retType, pyRes); @@ -1463,27 +1483,48 @@ module Python { /* Access an attribute/field of this Python object. This is equivalent to - calling ``obj[attr]`` or ``getattr(obj, attr)`` in Python. + calling ``getattr(obj, attr)`` or ``obj[attr]`` in Python. + + This method can be used as a general accessor for Python objects. + For example: + + .. + START_TEST + FILENAME: GetFac.chpl + START_GOOD + END_GOOD + + .. code-block:: chapel + + use Python; + var interp = new Interpreter(); + var mod = interp.importModule("math"); + + // the following two lines are equivalent + var fac1: Value = mod.get("factorial"); + var fac2: Value = new Function(mod, "factorial"); + + .. + END_TEST :arg t: The Chapel type of the value to return. :arg attr: The name of the attribute/field to access. */ pragma "docs only" - proc getAttr(type t=owned Value, attr: string): t throws do + proc get(type t=owned Value, attr: string): t throws do compilerError("docs only"); @chpldoc.nodoc - proc getAttr(type t, attr: string): t throws { - var pyAttr = PyObject_GetAttrString(this.get(), attr.c_str()); + proc get(type t, attr: string): t throws { + var pyAttr = PyObject_GetAttrString(this.getPyObject(), attr.c_str()); interpreter.checkException(); var res = interpreter.fromPython(t, pyAttr); return res; } @chpldoc.nodoc - proc getAttr(attr: string): owned Value throws do - return this.getAttr(owned Value, attr); - + proc get(attr: string): owned Value throws do + return this.get(owned Value, attr); /* Set an attribute/field of this Python object. This is equivalent to @@ -1492,11 +1533,11 @@ module Python { :arg attr: The name of the attribute/field to set. :arg value: The value to set the attribute/field to. */ - proc setAttr(attr: string, value) throws { + proc set(attr: string, value) throws { var pyValue = interpreter.toPython(value); defer Py_DECREF(pyValue); - PyObject_SetAttrString(this.get(), attr.c_str(), pyValue); + PyObject_SetAttrString(this.getPyObject(), attr.c_str(), pyValue); interpreter.checkException(); } @@ -1507,10 +1548,48 @@ module Python { :arg retType: The Chapel type of the return value. :arg method: The name of the method to call. :arg args: The arguments to pass to the method. + :arg kwargs: The keyword arguments to pass to the callable. */ pragma "docs only" - proc call(type retType = owned Value, method: string, const args...): retType throws do - compilerError("docs only"); + proc call(type retType = owned Value, + method: string, + const args..., + kwargs:?=none): retType throws + where kwargs.isAssociative() do compilerError("docs only"); + + pragma "last resort" + @chpldoc.nodoc + proc call(method: string, + type retType, + const args..., + kwargs:?=none): retType throws + where kwargs.isAssociative() { + var pyArg = this.packTuple((...args)); + defer Py_DECREF(pyArg); + + var methodFunc = + PyObject_GetAttrString(this.getPyObject(), method.c_str()); + this.check(); + defer Py_DECREF(methodFunc); + + return callInternal(retType, methodFunc, pyArg, kwargs); + } + pragma "last resort" + @chpldoc.nodoc + proc call(method: string,const args..., + kwargs:?=none): owned Value throws + where kwargs.isAssociative() { + var pyArg = this.packTuple((...args)); + defer Py_DECREF(pyArg); + + var methodFunc = + PyObject_GetAttrString(this.getPyObject(), method.c_str()); + this.check(); + defer Py_DECREF(methodFunc); + + return callInternal(owned Value, methodFunc, pyArg, kwargs); + } + @chpldoc.nodoc proc call(type retType, method: string, const args...): retType throws { @@ -1524,7 +1603,7 @@ module Python { defer Py_DECREF(methodName); var pyRes = PyObject_CallMethodObjArgs( - this.get(), methodName, (...pyArgs), nil); + this.getPyObject(), methodName, (...pyArgs), nil); interpreter.checkException(); var res = interpreter.fromPython(retType, pyRes); @@ -1539,7 +1618,7 @@ module Python { var methodName = interpreter.toPython(method); defer Py_DECREF(methodName); - var pyRes = PyObject_CallMethodNoArgs(this.get(), methodName); + var pyRes = PyObject_CallMethodNoArgs(this.getPyObject(), methodName); interpreter.checkException(); var res = interpreter.fromPython(retType, pyRes); @@ -1549,6 +1628,86 @@ module Python { proc call(method: string): owned Value throws do return this.call(owned Value, method); + + pragma "last resort" + @chpldoc.nodoc + proc call(type retType, + method: string, + kwargs:?=none): retType throws where kwargs.isAssociative() { + var pyArgs = Py_BuildValue("()"); + defer Py_DECREF(pyArgs); + + var methodFunc = + PyObject_GetAttrString(this.getPyObject(), method.c_str()); + this.check(); + defer Py_DECREF(methodFunc); + + return callInternal(retType, methodFunc, pyArgs, kwargs); + } + pragma "last resort" + @chpldoc.nodoc + proc call(method: string, + kwargs:?=none): owned Value throws where kwargs.isAssociative() { + return this.call(owned Value, method, kwargs=kwargs); + } + + + /* + Returns the Chapel value of the object. + + This is a shortcut for calling :proc:`~Interpreter.fromPython` on this + object, however it does not consume the object. + */ + proc value(type value) throws { + // fromPython will decrement the ref count, so we need to increment it + Py_INCREF(this.obj); + return interpreter.fromPython(value, this.obj); + } + + /* + Stop owning ``val``, returns the underlying ``c_ptr(PyObject)``. + + The caller is responsible for decrementing the reference count of the + returned object. + */ + proc type release(in val: owned Value): PyObjectPtr { + var valUn: unmanaged = owned.release(val); + valUn.isOwned = false; + var ptr: PyObjectPtr = valUn.obj; + delete valUn; + return ptr; + } + /* + Create a new :type:`Value`, adopting the object. + + When the new :type:`Value` is deleted, the reference count of the object + will be decremented. + */ + proc type adopting(in interpreter: borrowed Interpreter, + in object: PyObjectPtr): owned Value throws { + var val = new Value(interpreter, object, isOwned=true); + return val; + } + /* + Create a new :type:`Value`, adopting the object. + + When the new :type:`Value` is deleted, the reference count of the object + will be untouched. + */ + proc type borrowing(in interpreter: borrowed Interpreter, + in object: PyObjectPtr): owned Value throws { + var val = new Value(interpreter, object, isOwned=false); + return val; + } + + /* + Returns the :type:`~CTypes.c_ptr` to the underlying Python object. + + Most users should not need to call this method directly, except when + calling low-level CPython functions. + */ + proc getPyObject() do return this.obj; + // TODO: call should support kwargs } @@ -1560,7 +1719,7 @@ module Python { var modName: string; /* - Import a Python module by name. + Import a Python module by name. See :proc:`Interpreter.importModule`. */ proc init(interpreter: borrowed Interpreter, in modName: string) { super.init(interpreter, @@ -1570,6 +1729,7 @@ module Python { /* Import a Python module from a string using an arbitrary name. + See :proc:`Interpreter.importModule`. */ proc init(interpreter: borrowed Interpreter, in modName: string, in moduleContents: string) throws { @@ -1580,7 +1740,8 @@ module Python { } /* - Import a Python module from a string using an arbitrary name. + Import a Python module from bytecode using an arbitrary name. + See :proc:`Interpreter.importModule`. */ proc init(interpreter: borrowed Interpreter, in modName: string, in moduleBytecode: bytes) throws { @@ -1599,16 +1760,18 @@ module Python { var fnName: string; /* - Get a handle to a function in a :class:`Module` by name. + Get a handle to a function in a :class:`Value` by name. + + This is equivalent to ``mod.get(className)``. See :proc:`Value.get`. */ proc init(mod: borrowed Value, in fnName: string) { super.init(mod.interpreter, - PyObject_GetAttrString(mod.get(), fnName.c_str()), + PyObject_GetAttrString(mod.getPyObject(), fnName.c_str()), isOwned=true); this.fnName = fnName; } /* - Takes ownership of an existing Python object, pointed to by ``obj`` + Takes ownership of an existing Python object, pointed to by ``obj``. :arg interpreter: The interpreter that this object is associated with. :arg fnName: The name of the function. @@ -1621,8 +1784,8 @@ module Python { this.fnName = fnName; } /* - Create a new Python lambda function from a string. The lambda arguments must - have a trailing comma. + Create a new Python lambda function from a string. The lambda arguments + must have a trailing comma. For example, to create a lambda function that takes two arguments, use: @@ -1630,6 +1793,8 @@ module Python { new Function(interpreter, "lambda x, y,: x + y") + See also :proc:`Interpreter.compileLambda`. + :arg interpreter: The interpreter that this object is associated with. :arg lambdaFn: The lambda function to create. */ @@ -1637,7 +1802,7 @@ module Python { super.init(interpreter, nil: PyObjectPtr, isOwned=true); this.fnName = ""; init this; - this.obj = interpreter.compileLambda(lambdaFn); + this.obj = interpreter.compileLambdaInternal(lambdaFn); } @chpldoc.nodoc proc init(in interpreter: borrowed Interpreter, @@ -1656,14 +1821,16 @@ module Python { var className: string; /* - Get a handle to a class in a :class:`Module` by name. + Get a handle to a class in a :class:`Value` by name. + + This is equivalent to ``mod.get(className)``. See :proc:`Value.get`. :arg mod: The module to get the class from. :arg className: The name of the class. */ proc init(mod: borrowed Value, in className: string) { super.init(mod.interpreter, - PyObject_GetAttrString(mod.get(), className.c_str()), + PyObject_GetAttrString(mod.getPyObject(), className.c_str()), isOwned=true); this.className = className; } @@ -1694,7 +1861,7 @@ module Python { :returns: The size of the list. */ proc size: int throws { - var size = PySequence_Size(this.get()); + var size = PySequence_Size(this.getPyObject()); this.check(); return size; } @@ -1707,18 +1874,18 @@ module Python { :returns: The item at the given index. */ pragma "docs only" - proc getItem(type T = owned Value, idx: int): T throws do + proc get(type T = owned Value, idx: int): T throws do compilerError("docs only"); @chpldoc.nodoc - proc getItem(type T, idx: int): T throws { - var item = PySequence_GetItem(this.get(), idx.safeCast(Py_ssize_t)); + proc get(type T, idx: int): T throws { + var item = PySequence_GetItem(this.getPyObject(), idx.safeCast(Py_ssize_t)); this.check(); return interpreter.fromPython(T, item); } @chpldoc.nodoc - proc getItem(idx: int): owned Value throws do - return this.getItem(owned Value, idx); + proc get(idx: int): owned Value throws do + return this.get(owned Value, idx); /* Set an item in the list. Equivalent to calling ``obj[idx] = item`` in @@ -1727,8 +1894,8 @@ module Python { :arg idx: The index of the item to set. :arg item: The item to set. */ - proc setItem(idx: int, item: ?) throws { - PySequence_SetItem(this.get(), + proc set(idx: int, item: ?) throws { + PySequence_SetItem(this.getPyObject(), idx.safeCast(Py_ssize_t), interpreter.toPython(item)); this.check(); @@ -1787,12 +1954,12 @@ module Python { } @chpldoc.nodoc proc postinit() throws { - if PyObject_CheckBuffer(this.get()) == 0 { + if PyObject_CheckBuffer(this.getPyObject()) == 0 { throw new ChapelException("Object does not support buffer protocol"); } var flags: c_int = PyBUF_SIMPLE | PyBUF_WRITABLE | PyBUF_FORMAT | PyBUF_ND; - if PyObject_GetBuffer(this.get(), c_ptrTo(this.view), flags) == -1 { + if PyObject_GetBuffer(this.getPyObject(), c_ptrTo(this.view), flags) == -1 { this.check(); // this.check should have raised an exception, if it didn't, raise one throw new BufferError("Failed to get buffer"); @@ -1848,7 +2015,7 @@ module Python { While Chapel arrays can be indexed arbitrarily by specifying a domain (e.g. ``var myArr: [2..by 4 #2]``), the equivalent Python array will also by indexed starting at 0 with a stride of 1. Methods like - :proc:`~Array.getItem` do no translation of the domain and should be + :proc:`~Array.get` do no translation of the domain and should be called with the Python interpretation of the index. @@ -1907,7 +2074,7 @@ module Python { :returns: The size of the array. */ proc size: int throws { - var size = PySequence_Size(this.get()); + var size = PySequence_Size(this.getPyObject()); this.check(); return size; } @@ -1919,8 +2086,8 @@ module Python { :arg idx: The index of the item to get. :returns: The item at the given index. */ - proc getItem(idx: int): eltType throws { - var pyObj = PySequence_GetItem(this.get(), idx.safeCast(Py_ssize_t)); + proc get(idx: int): eltType throws { + var pyObj = PySequence_GetItem(this.getPyObject(), idx.safeCast(Py_ssize_t)); this.check(); return interpreter.fromPython(eltType, pyObj); } @@ -1931,9 +2098,9 @@ module Python { :arg idx: The index of the item to set. :arg item: The item to set. */ - proc setItem(idx: int, item: eltType) throws { + proc set(idx: int, item: eltType) throws { var pyItem = interpreter.toPython(item); - PySequence_SetItem(this.get(), idx.safeCast(Py_ssize_t), pyItem); + PySequence_SetItem(this.getPyObject(), idx.safeCast(Py_ssize_t), pyItem); this.check(); } } diff --git a/test/library/packages/Python/correctness/argPassingTest.chpl b/test/library/packages/Python/correctness/argPassingTest.chpl index 8bda201991b2..34a1d9ea3eb6 100644 --- a/test/library/packages/Python/correctness/argPassingTest.chpl +++ b/test/library/packages/Python/correctness/argPassingTest.chpl @@ -4,7 +4,7 @@ use IO; proc test_no_args(mod: borrowed Module) { const funcName = "no_args"; - var func = new Function(mod, funcName); + var func = mod.get(funcName); func(NoneType); func(); @@ -21,7 +21,7 @@ proc test_no_args(mod: borrowed Module) { } proc test_one_arg(mod: borrowed Module) { const funcName = "one_arg"; - var func = new Function(mod, funcName); + var func = mod.get(funcName); func(NoneType, 1); func(2); @@ -38,7 +38,7 @@ proc test_one_arg(mod: borrowed Module) { } proc test_two_args(mod: borrowed Module) { const funcName = "two_args"; - var func = new Function(mod, funcName); + var func = mod.get(funcName); func(NoneType, 1, 2); func("hello", "world"); @@ -51,13 +51,13 @@ proc test_two_args(mod: borrowed Module) { } proc test_three_args(mod: borrowed Module) { const funcName = "three_args"; - var func = new Function(mod, funcName); + var func = mod.get(funcName); func(NoneType, 1, 2, 3); } proc test_varargs(mod: borrowed Module) { const funcName = "varargs"; - var func = new Function(mod, funcName); + var func = mod.get(funcName); func(NoneType); func(1); @@ -70,7 +70,7 @@ proc test_varargs(mod: borrowed Module) { } proc test_one_arg_with_default(mod: borrowed Module) { const funcName = "one_arg_with_default"; - var func = new Function(mod, funcName); + var func = mod.get(funcName); func(NoneType); func(NoneType, 7); @@ -79,7 +79,7 @@ proc test_one_arg_with_default(mod: borrowed Module) { } proc test_three_args_with_default(mod: borrowed Module) { const funcName = "three_args_with_default"; - var func = new Function(mod, funcName); + var func = mod.get(funcName); func(NoneType, 8); func(NoneType, 8, 9); @@ -89,7 +89,7 @@ proc test_three_args_with_default(mod: borrowed Module) { } proc test_three_args_with_default_and_kwargs(mod: borrowed Module) { const funcName = "three_args_with_default_and_kwargs"; - var func = new Function(mod, funcName); + var func = mod.get(funcName); func(NoneType, 8); func(NoneType, 8, 9); @@ -99,7 +99,7 @@ proc test_three_args_with_default_and_kwargs(mod: borrowed Module) { } proc test_varargs_and_kwargs(mod: borrowed Module) { const funcName = "varargs_and_kwargs"; - var func = new Function(mod, funcName); + var func = mod.get(funcName); func(NoneType); func(NoneType, 1); @@ -115,7 +115,7 @@ proc main() { var interp = new Interpreter(); var modName = Reflection.getModuleName(); - var m = new Module(interp, modName); + var m = interp.importModule(modName); test_no_args(m); test_one_arg(m); diff --git a/test/library/packages/Python/correctness/arrays/gradient.chpl b/test/library/packages/Python/correctness/arrays/gradient.chpl index 67f70b03822a..4b99e0d1363a 100644 --- a/test/library/packages/Python/correctness/arrays/gradient.chpl +++ b/test/library/packages/Python/correctness/arrays/gradient.chpl @@ -19,9 +19,9 @@ def grad(arr): proc main() { var interp = new Interpreter(); - var mod = new Module(interp, '__empty__', code); - var gradModifyArg = new Function(mod, 'gradModifyArg'); - var grad = new Function(mod, 'grad'); + var mod = interp.importModule('__empty__', code); + var gradModifyArg = mod.get('gradModifyArg'); + var grad = mod.get('grad'); var arr = [1, 2, 4, 7, 11, 16]; var pyArr = new Array(interp, arr); diff --git a/test/library/packages/Python/correctness/arrays/myArray.chpl b/test/library/packages/Python/correctness/arrays/myArray.chpl index 1a408941e7fb..21f3d222b580 100644 --- a/test/library/packages/Python/correctness/arrays/myArray.chpl +++ b/test/library/packages/Python/correctness/arrays/myArray.chpl @@ -31,18 +31,18 @@ proc testArray(type t, const testArr) { var pyArr = new Array(interp, arr); writeln("python: ", pyArr); - pyArr.setItem(0, 17:t); - writeln("at 2: ", pyArr.getItem(2)); - writeln("at -1: ", pyArr.getItem(-1)); - pyArr.setItem(-2, 42:t); + pyArr.set(0, 17:t); + writeln("at 2: ", pyArr.get(2)); + writeln("at -1: ", pyArr.get(-1)); + pyArr.set(-2, 42:t); writeln("size: ", pyArr.size); writeln("chapel: ", arr); IO.stdout.flush(); writeln("from python"); IO.stdout.flush(); - var pyCode = new Module(interp, '__empty__', pythonCode); - var func = new Function(pyCode, 'loop'); + var pyCode = interp.importModule('__empty__', pythonCode); + var func = pyCode.get('loop'); func(pyArr); IO.stdout.flush(); diff --git a/test/library/packages/Python/correctness/arrays/myArrayReturnArray.chpl b/test/library/packages/Python/correctness/arrays/myArrayReturnArray.chpl index 004fa2574f41..8acc63b031e3 100644 --- a/test/library/packages/Python/correctness/arrays/myArrayReturnArray.chpl +++ b/test/library/packages/Python/correctness/arrays/myArrayReturnArray.chpl @@ -11,8 +11,8 @@ proc main() { var interp = new Interpreter(); var pyArr = new Array(interp, arr); - var pyCode = new Module(interp, '__empty__', pythonCode); - var func = new Function(pyCode, 'returnSelf'); + var pyCode = interp.importModule('__empty__', pythonCode); + var func = pyCode.get('returnSelf'); var newArr = func(owned Array, pyArr); writeln("from chapel: ", newArr); } diff --git a/test/library/packages/Python/correctness/arrays/myArrayReturnArray.good b/test/library/packages/Python/correctness/arrays/myArrayReturnArray.good index f49226003156..131100faa16d 100644 --- a/test/library/packages/Python/correctness/arrays/myArrayReturnArray.good +++ b/test/library/packages/Python/correctness/arrays/myArrayReturnArray.good @@ -1,4 +1,4 @@ $CHPL_HOME/modules/packages/Python.chpl:nnnn: In method 'callInternal': $CHPL_HOME/modules/packages/Python.chpl:nnnn: error: Cannot create an Array from an existing PyObject - $CHPL_HOME/modules/packages/Python.chpl:nnnn: called as Value.callInternal(type retType = owned Array(nothing), pyArg: c_ptr(PyObject), kwargs: nothing) from method 'this' + $CHPL_HOME/modules/packages/Python.chpl:nnnn: called as Value.callInternal(type retType = owned Array(nothing), pyFunc: c_ptr(PyObject), pyArg: c_ptr(PyObject), kwargs: nothing) from method 'this' myArrayReturnArray.chpl:16: called as Value.this(type retType = owned Array(nothing), args(0): owned Array(int(64))) diff --git a/test/library/packages/Python/correctness/arrays/myList.chpl b/test/library/packages/Python/correctness/arrays/myList.chpl index da6c718ae522..13185bb7d3d5 100644 --- a/test/library/packages/Python/correctness/arrays/myList.chpl +++ b/test/library/packages/Python/correctness/arrays/myList.chpl @@ -10,28 +10,28 @@ proc main() { var interp = new Interpreter(); - var pyCodeModule = new Module(interp, '__empty__', pyCode); - var getListFunc = new Function(pyCodeModule, 'getList'); + var pyCodeModule = interp.importModule('__empty__', pyCode); + var getListFunc = pyCodeModule.get('getList'); var lst = getListFunc(owned PyList); writeln("lst ", lst); writeln("size ", lst.size); - writeln("lst[0] ", lst.getItem(int, 0)); - writeln("lst[1] ", lst.getItem(int, 1)); - writeln("lst[2] ", lst.getItem(string, 2)); - writeln("lst[lst.size-1] ", lst.getItem(int, lst.size-1)); - writeln("lst[-3] ", lst.getItem(owned Value, -3)); - writeln("lst[-3] ", lst.getItem(-3)); + writeln("lst[0] ", lst.get(int, 0)); + writeln("lst[1] ", lst.get(int, 1)); + writeln("lst[2] ", lst.get(string, 2)); + writeln("lst[lst.size-1] ", lst.get(int, lst.size-1)); + writeln("lst[-3] ", lst.get(owned Value, -3)); + writeln("lst[-3] ", lst.get(-3)); try { write("lst[lst.size] "); - writeln(lst.getItem(int, lst.size)); + writeln(lst.get(int, lst.size)); } catch e: PythonException { writeln("Caught exception: ", e); } catch e{ writeln("Caught unknown exception: ", e); } - lst.setItem(0, 100); + lst.set(0, 100); writeln("lst ", lst); } diff --git a/test/library/packages/Python/correctness/arrays/nestedArrays.chpl b/test/library/packages/Python/correctness/arrays/nestedArrays.chpl index 2a5f0ffc6ee2..c25b532597db 100644 --- a/test/library/packages/Python/correctness/arrays/nestedArrays.chpl +++ b/test/library/packages/Python/correctness/arrays/nestedArrays.chpl @@ -5,8 +5,8 @@ use Python; proc main() { var interp = new Interpreter(); - var m = new Module(interp, 'nestedArrays'); - var strNested = new Function(m, "strNested"); + var m = interp.importModule('nestedArrays'); + var strNested = m.get("strNested"); { var input = [[1, 2], [3, 4]]; diff --git a/test/library/packages/Python/correctness/arrays/numpyInterop.chpl b/test/library/packages/Python/correctness/arrays/numpyInterop.chpl index ce6db9b8f1e4..d61878ce8e26 100644 --- a/test/library/packages/Python/correctness/arrays/numpyInterop.chpl +++ b/test/library/packages/Python/correctness/arrays/numpyInterop.chpl @@ -17,9 +17,9 @@ def numpyAssign(arr): proc main() { var interp = new Interpreter(); - var m = new Module(interp, '__empty__', code); - var saxpy = new Function(m, 'saxpy'); - var numpyAssign = new Function(m, 'numpyAssign'); + var m = interp.importModule('__empty__', code); + var saxpy = m.get('saxpy'); + var numpyAssign = m.get('numpyAssign'); { var x = [1, 2, 3]; diff --git a/test/library/packages/Python/correctness/arrays/usePythonArray.chpl b/test/library/packages/Python/correctness/arrays/usePythonArray.chpl index 56cffc1b526f..8f452cf455a8 100644 --- a/test/library/packages/Python/correctness/arrays/usePythonArray.chpl +++ b/test/library/packages/Python/correctness/arrays/usePythonArray.chpl @@ -2,8 +2,8 @@ use Python; proc main() { var interp = new Interpreter(); - var mod = new Module(interp, "usePythonArray"); - var doit = new Function(mod, 'doit'); + var mod = interp.importModule("usePythonArray"); + var doit = mod.get('doit'); var pyRes = doit(owned PyArray(int), 10, 11, 12, 13); diff --git a/test/library/packages/Python/correctness/basicTypes.chpl b/test/library/packages/Python/correctness/basicTypes.chpl index a283fca3e2ff..73802a9f43ba 100644 --- a/test/library/packages/Python/correctness/basicTypes.chpl +++ b/test/library/packages/Python/correctness/basicTypes.chpl @@ -43,17 +43,17 @@ proc roundTripClass(clsType: borrowed) { var obj = clsType(value); if print then writeln(" obj: ", obj); - res = obj.getAttr(t, "value"); + res = obj.get(t, "value"); if print then writeln(" obj.value: ", res); assert(res == value); - obj.setAttr("value", other); + obj.set("value", other); res = obj.call(t, "getter"); if print then writeln(" obj.getter(): ", res); assert(res == other); obj.call("setter", value); - res = obj.getAttr(t, "value"); + res = obj.get(t, "value"); if print then writeln(" obj.value: ", res); assert(res == value); @@ -83,14 +83,14 @@ proc main() { var interp = new Interpreter(); var modName = Reflection.getModuleName(); - var m = new Module(interp, modName); + var m = interp.importModule(modName); if print then writeln("module: ", m); - var func = new Function(m, "round_trip"); + var func = m.get("round_trip"); if print then writeln("func: ", func); roundTripFunction(func); - var clsType = new Class(m, "RoundTrip"); + var clsType = m.get("RoundTrip"); if print then writeln("class: ", clsType); roundTripClass(clsType); diff --git a/test/library/packages/Python/correctness/compareIterationPatterns.chpl b/test/library/packages/Python/correctness/compareIterationPatterns.chpl index 77d301567c36..3c5e9f1d1aea 100644 --- a/test/library/packages/Python/correctness/compareIterationPatterns.chpl +++ b/test/library/packages/Python/correctness/compareIterationPatterns.chpl @@ -46,7 +46,7 @@ proc parallelPythonApplySubInterp(interp: borrowed, type t, arr, l) { proc init(parent: borrowed, s) { init this; interp = try! (new SubInterpreter(parent)); - func = try! (new Function(interp!, s)); + func = try! (interp!.compileLambda(s)); } inline proc this(type t, a) throws { return func!(t, a); diff --git a/test/library/packages/Python/correctness/customType.chpl b/test/library/packages/Python/correctness/customType.chpl index a19b4afe2d46..da6b4feffaad 100644 --- a/test/library/packages/Python/correctness/customType.chpl +++ b/test/library/packages/Python/correctness/customType.chpl @@ -9,7 +9,7 @@ record myRec { } class myRecConverter: TypeConverter { - var pyClsType: borrowed Class; + var pyClsType: borrowed Value; override proc handlesType(type T): bool { return T == myRec; } @@ -22,7 +22,7 @@ class myRecConverter: TypeConverter { type T, obj: Python.CPythonInterface.PyObjectPtr): T throws { if T != myRec then halt("Expected myRec"); var cls = new Value(interpreter, obj); - var res = new myRec(cls.getAttr(int, "x"), cls.getAttr(string, "y")); + var res = new myRec(cls.get(int, "x"), cls.get(string, "y")); return res; } } @@ -31,13 +31,13 @@ proc main() { var interp = new Interpreter(); var modName = Reflection.getModuleName(); - var m = new Module(interp, modName); + var m = interp.importModule(modName); - var pyClsType = new Class(m, "MyRec"); + var pyClsType = m.get("MyRec"); interp.registerConverter(new myRecConverter(pyClsType)); IO.stdout.flush(); - var printAndReturn = new Function(m, "printAndReturn"); + var printAndReturn = m.get("printAndReturn"); var fromPy = printAndReturn(myRec, new myRec(42, "hello")); writeln(fromPy); } diff --git a/test/library/packages/Python/correctness/defaultType.chpl b/test/library/packages/Python/correctness/defaultType.chpl index 477e0c1ecc85..4272c95a8099 100644 --- a/test/library/packages/Python/correctness/defaultType.chpl +++ b/test/library/packages/Python/correctness/defaultType.chpl @@ -11,10 +11,10 @@ def pass_through(x): """; var interp = new Interpreter(); -var mod = new Module(interp, '__empty__', code); -var do_nothing = new Function(mod, 'do_nothing'); -var get_int = new Function(mod, 'get_int'); -var pass_through = new Function(mod, 'pass_through'); +var mod = interp.importModule('__empty__', code); +var do_nothing = mod.get('do_nothing'); +var get_int = mod.get('get_int'); +var pass_through = mod.get('pass_through'); { writeln("do_nothing()"); diff --git a/test/library/packages/Python/correctness/directCalls.chpl b/test/library/packages/Python/correctness/directCalls.chpl new file mode 100644 index 000000000000..2adb5d1f8d06 --- /dev/null +++ b/test/library/packages/Python/correctness/directCalls.chpl @@ -0,0 +1,46 @@ + +use Python; + +var code = """ +class C: + def __init__(self): + self.x = 17 + def foo(self): + return self.x + +def bar(): + return 18 +"""; + +var interp = new Interpreter(); +var mod = interp.importModule('__empty__', code); + +{ + var res1 = mod.call('bar'); + + var bar = mod.get('bar'); + var res2 = bar(); + + var res3 = mod.get('bar')(); + + // these are all the same + writeln("mod.call('bar'): ", res1); + writeln("bar(): ", res2); + writeln("mod.get('bar')(): ", res3); +} + +{ + var C = mod.get('C'); + var c = C(); + var res1 = c.call('foo'); + + var foo = c.get('foo'); + var res2 = foo(); + + var res3 = mod.get('C')().call('foo'); + + // these are all the same + writeln("c.call('foo'): ", res1); + writeln("foo(): ", res2); + writeln("mod.get('C')().call('foo'): ", res3); +} diff --git a/test/library/packages/Python/correctness/directCalls.good b/test/library/packages/Python/correctness/directCalls.good new file mode 100644 index 000000000000..44f124a77cf0 --- /dev/null +++ b/test/library/packages/Python/correctness/directCalls.good @@ -0,0 +1,6 @@ +mod.call('bar'): 18 +bar(): 18 +mod.get('bar')(): 18 +c.call('foo'): 17 +foo(): 17 +mod.get('C')().call('foo'): 17 diff --git a/test/library/packages/Python/correctness/iteratorTest.chpl b/test/library/packages/Python/correctness/iteratorTest.chpl index 4d76888d7247..d99edc4b78a0 100644 --- a/test/library/packages/Python/correctness/iteratorTest.chpl +++ b/test/library/packages/Python/correctness/iteratorTest.chpl @@ -43,7 +43,7 @@ proc main() { var interp = new Interpreter(); var modName = Reflection.getModuleName(); - var m = new Module(interp, modName); + var m = interp.importModule(modName); var myiter = new Function(m, "myiter"); test(myiter); diff --git a/test/library/packages/Python/correctness/loadingCode/moduleFromBytes.chpl b/test/library/packages/Python/correctness/loadingCode/moduleFromBytes.chpl index 8ca7c3a265da..c4870bdbe904 100644 --- a/test/library/packages/Python/correctness/loadingCode/moduleFromBytes.chpl +++ b/test/library/packages/Python/correctness/loadingCode/moduleFromBytes.chpl @@ -6,10 +6,10 @@ use Python; var interp = new Interpreter(); var modBytes = interp.loadPycFile(pycPath); -var mod = new Module(interp, "mod", modBytes); +var mod = interp.importModule("mod", modBytes); // get MyClass and my_function -var MyClass = new Class(mod, "MyClass"); -var my_function = new Function(mod, "my_function"); +var MyClass = mod.get("MyClass"); +var my_function = mod.get("my_function"); // run my_function var v = my_function(); diff --git a/test/library/packages/Python/correctness/loadingCode/moduleFromString.chpl b/test/library/packages/Python/correctness/loadingCode/moduleFromString.chpl index 00ba26df740e..9e6b3dee4efa 100644 --- a/test/library/packages/Python/correctness/loadingCode/moduleFromString.chpl +++ b/test/library/packages/Python/correctness/loadingCode/moduleFromString.chpl @@ -8,8 +8,8 @@ def foo(x): var interp = new Interpreter(); -var mod = new Module(interp, "mymod", modStr); -var foo = mod.getAttr(owned Function, "foo"); +var mod = interp.importModule("mymod", modStr); +var foo = mod.get(owned Function, "foo"); foo(1); foo([1,2,3]); foo("str"); diff --git a/test/library/packages/Python/correctness/noExceptions.chpl b/test/library/packages/Python/correctness/noExceptions.chpl index f5b9a89013dd..3a0673a0bb9e 100644 --- a/test/library/packages/Python/correctness/noExceptions.chpl +++ b/test/library/packages/Python/correctness/noExceptions.chpl @@ -10,20 +10,20 @@ raise Exception('Hello, World!') // use default checking { var interp = new Interpreter(); - var mod = new Module(interp, 'hello', hello); + var mod = interp.importModule('hello', hello); } // explicitly use no checking, blocked by https://github.com/chapel-lang/chapel/issues/26579 { var interp = new Interpreter(checkExceptions=false); - var mod = new Module(interp, 'hello', hello); + var mod = interp.importModule('hello', hello); } // explicitly use checking, blocked by https://github.com/chapel-lang/chapel/issues/26579 { var interp = new Interpreter(checkExceptions=true); try { - var mod = new Module(interp, 'hello', hello_raise); + var mod = interp.importModule('hello', hello_raise); } catch e: PythonException { writeln("Caught exception: ", e.message()); } catch { diff --git a/test/library/packages/Python/correctness/subInterp.chpl b/test/library/packages/Python/correctness/subInterp.chpl index b5641f030d92..9bc5479d0ff1 100644 --- a/test/library/packages/Python/correctness/subInterp.chpl +++ b/test/library/packages/Python/correctness/subInterp.chpl @@ -17,8 +17,8 @@ proc main() { coforall tid in 0..#tasks { var localInterp = new SubInterpreter(interp); - var m = new Module(localInterp, '__empty__', code); - var f = new Function(m, 'hello'); + var m = localInterp.importModule('__empty__', code); + var f = m.get('hello'); for i in 1..#itersPerTask { f(tid, i); } diff --git a/test/library/packages/Python/correctness/twoModules.chpl b/test/library/packages/Python/correctness/twoModules.chpl new file mode 100644 index 000000000000..ac44686289e9 --- /dev/null +++ b/test/library/packages/Python/correctness/twoModules.chpl @@ -0,0 +1,20 @@ +use Python; + +var interp = new Interpreter(); + +var code = """ +def foo(): + return 42 +"""; +var code2 = """ +def foo(): + return 55 +"""; + +var mod = new Module(interp, "mymod", code); +writeln(mod.get("foo")()); // 42 + +var mod2 = new Module(interp, "mymod", code2); + +writeln(mod2.get("foo")()); // 55 +writeln(mod.get("foo")()); // 55, the old module was replaced diff --git a/test/library/packages/Python/correctness/twoModules.good b/test/library/packages/Python/correctness/twoModules.good new file mode 100644 index 000000000000..34e3d8091abb --- /dev/null +++ b/test/library/packages/Python/correctness/twoModules.good @@ -0,0 +1,3 @@ +42 +55 +55 diff --git a/test/library/packages/Python/examples/bs4/findLinks.chpl b/test/library/packages/Python/examples/bs4/findLinks.chpl index c10dd253cd0a..e7b4f9d00b81 100644 --- a/test/library/packages/Python/examples/bs4/findLinks.chpl +++ b/test/library/packages/Python/examples/bs4/findLinks.chpl @@ -20,15 +20,15 @@ const html = proc main() { var interp = new Interpreter(); - var mod = new Module(interp, "bs4"); + var mod = interp.importModule("bs4"); - var cls = new Class(mod, "BeautifulSoup"); + var cls = mod.get("BeautifulSoup"); var soup = cls(html, 'html.parser'); var res: list(owned Value?); res = soup.call(res.type, "find_all", "a"); for c in res { - var linkText = c!.getAttr(string, "text"); + var linkText = c!.get(string, "text"); var linkUrl = c!.call(string, "__getitem__", "href"); writeln(linkText, ": ", linkUrl); } diff --git a/test/library/packages/Python/examples/numba/apply.chpl b/test/library/packages/Python/examples/numba/apply.chpl index 86110a5a2cdd..96afa5ede678 100644 --- a/test/library/packages/Python/examples/numba/apply.chpl +++ b/test/library/packages/Python/examples/numba/apply.chpl @@ -10,7 +10,7 @@ config const timeit = false; require "callFuncGadget.h"; extern proc callFunc(func: c_ptr(void), x: c_long): c_long; -proc callApply(arr, func: borrowed Function) { +proc callApply(arr, func: borrowed Value) { var res: arr.type; for i in arr.domain { res(i) = func(res.eltType, arr(i)); @@ -34,11 +34,15 @@ proc main() { var interp = new Interpreter(); - // Ideally we could just write the function in a Chapel string and compile it, - // but thats not possible yet - var lib = new Module(interp, "lib"); - var applyFunc = new Function(lib, "apply"); - var applyFuncAddr = applyFunc.getAttr(c_intptr, "address"): c_ptr(void); + var numba_code = """ +import numba +@numba.cfunc(numba.int64(numba.int64)) +def apply(x): + return x + 1 if x % 2 != 0 else x + """; + var lib = interp.importModule("lib", numba_code); + var applyFunc = lib.get("apply"); + var applyFuncAddr = applyFunc.get(c_intptr, "address"): c_ptr(void); { data = 1:c_long..#n:c_long; diff --git a/test/library/packages/Python/examples/numba/lib.py b/test/library/packages/Python/examples/numba/lib.py deleted file mode 100644 index ecab394f295a..000000000000 --- a/test/library/packages/Python/examples/numba/lib.py +++ /dev/null @@ -1,5 +0,0 @@ -import numba - -@numba.cfunc(numba.int64(numba.int64)) -def apply(x): - return x + 1 if x % 2 != 0 else x diff --git a/test/library/packages/Python/examples/torch/myModel.chpl b/test/library/packages/Python/examples/torch/myModel.chpl index 05f07ec59110..24d85f20d6e9 100644 --- a/test/library/packages/Python/examples/torch/myModel.chpl +++ b/test/library/packages/Python/examples/torch/myModel.chpl @@ -6,14 +6,14 @@ proc main() { var interp = new Interpreter(); // imports from mymodel - var myModelModule = new Module(interp, "mymodel"); - var myModelClass = new Class(myModelModule, "MyModel"); + var myModelModule = interp.importModule("mymodel"); + var myModelClass = myModelModule.get("MyModel"); // imports from torch - var torch = new Module(interp, "torch"); - var tensor = new Function(torch, "tensor"); - var nn = new Module(interp, "torch.nn"); - var MSELoss = new Class(nn, "MSELoss"); + var torch = interp.importModule("torch"); + var tensor = torch.get("tensor"); + var nn = interp.importModule("torch.nn"); + var MSELoss = nn.get("MSELoss"); // create the model var model = myModelClass(); @@ -24,7 +24,7 @@ proc main() { { var params = model.call(list(owned Value?), "parameters"); for p in params { - var data_ = p!.getAttr("data"); + var data_ = p!.get("data"); data_.call("fill_", 0.9); } } @@ -43,11 +43,11 @@ proc main() { var learning_rate = 0.01; var params = model.call(list(owned Value?), "parameters"); for p in params { - var data = p!.getAttr("data"); - var grad = p!.getAttr("grad"); + var data = p!.get("data"); + var grad = p!.get("grad"); var temp = grad.call("__mul__", learning_rate); var temp2 = data.call("__sub__", temp); - p!.setAttr("data", temp2); + p!.set("data", temp2); } writeln("Prediction: ", pred.call(real, "item")); diff --git a/test/library/packages/Python/memleaks/lambdas.chpl b/test/library/packages/Python/memleaks/lambdas.chpl index 5388ea8560c7..e5a6179a496b 100644 --- a/test/library/packages/Python/memleaks/lambdas.chpl +++ b/test/library/packages/Python/memleaks/lambdas.chpl @@ -4,7 +4,7 @@ proc main() { var interp = new Interpreter(); - var l = new Function(interp, "lambda x,: [x] + [x]"); + var l = interp.compileLambda("lambda x,: [x] + [x]"); writeln(l(list(int), 1)); writeln(l(list(string), "hi")); @@ -12,14 +12,14 @@ proc main() { writeln(l(list(list(int)), [1, 2, 3])); // chapelList([4,5,6]) - var l2 = new Function(interp, "lambda x,y,z,: [x,y,z]"); + var l2 = interp.compileLambda("lambda x,y,z,: [x,y,z]"); // printing this out will cause a memleak, the __str__ method for list leaks // e.g., 'print([[1,2,3])' in python leaks memory l2(list(owned Value?), 1, "hi", [4, 5, 6]); writeln("skipping potentially leaking print"); - var l3 = new Function(interp, "lambda x,: x"); + var l3 = interp.compileLambda("lambda x,: x"); writeln(l3(list(int), [1,])); writeln(l3(NoneType, [1,])); }