Repository: pyccel/pyccel
Pull request #1734 (2024-02-16 09:32:44)

List support: clear method 
Add support for the pop() method of Python lists to the semantic stage.
Add handling of that method to the Python printer. This fixes : #1691.

mustapha-belbiad: /bot checklist
pyccel-bot[bot]: Hey @pyccel/pyccel-dev ! @mustapha-belbiad has just created this great new pull request! Check it out and let me know what you think!

pyccel-bot[bot]: Hey @yguclu, @EmilyBourne, this PR is looking pretty good. @mustapha-belbiad and @Farouk-Echaref think it is ready to merge. Could you add your expertise to confirm that this follows all the coding conventions and fits in Pyccel's future plans? Thanks :smile:

pyccel-bot[bot]: @mustapha-belbiad, @EmilyBourne has a few questions/comments about your code. Can you go through and see if you agree with them. If not go ahead and explain why. Once you've adressed all the comments let me know with `/bot mark as ready` and we will see if we can get approval.

pyccel-bot[bot]: @EmilyBourne, @mustapha-belbiad has been working hard and thinks that they have now replied to or fixed all your comments. Could you take another look at the PR and see if you can approve now?

pyccel-bot[bot]: @mustapha-belbiad, @yguclu has a few questions/comments about your code. Can you go through and see if you agree with them. If not go ahead and explain why. Once you've adressed all the comments let me know with `/bot mark as ready` and we will see if we can get approval.


Patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 624d360a..fb03947f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,8 +6,9 @@ All notable changes to this project will be documented in this file.
 ### Added
 
 -   #1529 : Add Python support for list method `append()`
--   #1690 : Add support for `pop()` method of list class
+-   #1690 : Add Python support for list method `pop()`
 -   #1575 : Add support for homogeneous tuple type annotations on variables.
+-   #1691 : Add Python support for list method `clear()`
 
 ### Fixed
 
diff --git a/pyccel/ast/builtin_methods/list_methods.py b/pyccel/ast/builtin_methods/list_methods.py
index 859f7dc5..0383b8c6 100644
--- a/pyccel/ast/builtin_methods/list_methods.py
+++ b/pyccel/ast/builtin_methods/list_methods.py
@@ -14,7 +14,10 @@ from pyccel.ast.datatypes import NativeVoid, NativeGeneric, NativeHomogeneousLis
 from pyccel.ast.internals import PyccelInternalFunction
 
 
-__all__ = ('ListAppend','ListPop')
+__all__ = ('ListAppend',
+           'ListClear',
+           'ListPop'
+           )
 
 
 class ListAppend(PyccelInternalFunction):
@@ -130,3 +133,39 @@ class ListPop(PyccelInternalFunction) :
         """
         return self._list_variable
 
+#==============================================================================
+class ListClear(PyccelInternalFunction) :
+    """
+    Represents a call to the .clear() method.
+    
+    Represents a call to the .clear() method which deletes all elements from a list, 
+    effectively turning it into an empty list.
+    Note that the .clear() method doesn't return any value.
+
+    Parameters
+    ----------
+    list_variable : TypedAstNode
+        The name of the list.
+    """
+    __slots__ = ('_list_variable',)
+    _attribute_nodes = ('_list_variable',)
+    _dtype = NativeVoid()
+    _precision = -1
+    _rank = 0
+    _order = None
+    _shape = None
+    _class_type = NativeHomogeneousList()
+    name = 'clear'
+
+    def __init__(self, list_variable):
+        self._list_variable = list_variable
+        super().__init__()
+
+    @property
+    def list_variable(self):
+        """
+        Provide the name of the list as the return value.
+
+        Provide the name of the list as the return value.
+        """
+        return self._list_variable
diff --git a/pyccel/ast/class_defs.py b/pyccel/ast/class_defs.py
index 1a9abba8..502bceb0 100644
--- a/pyccel/ast/class_defs.py
+++ b/pyccel/ast/class_defs.py
@@ -6,7 +6,7 @@
 This module contains all types which define a python class which is automatically recognised by pyccel
 """
 
-from pyccel.ast.builtin_methods.list_methods import ListAppend, ListPop
+from pyccel.ast.builtin_methods.list_methods import ListAppend, ListPop, ListClear
 
 
 from .builtins  import PythonImag, PythonReal, PythonConjugate
@@ -141,6 +141,8 @@ ListClass = ClassDef('list', class_type = NativeHomogeneousList(),
                 decorators = {}),
             PyccelFunctionDef('pop', func_class = ListPop,
                 decorators = {}),
+            PyccelFunctionDef('clear', func_class = ListClear,
+                decorators = {}),
         ])
 
 #=======================================================================================
diff --git a/pyccel/codegen/printing/pycode.py b/pyccel/codegen/printing/pycode.py
index b8bdc3a6..fb24a9dd 100644
--- a/pyccel/codegen/printing/pycode.py
+++ b/pyccel/codegen/printing/pycode.py
@@ -852,6 +852,15 @@ class PythonCodePrinter(CodePrinter):
 
         return f"{list_var}.{method_name}({append_arg})\n"
 
+    def _print_ListPop(self, expr):
+        args = self._print(expr.pop_index) if expr.pop_index else ""
+        name = self._print(expr.list_variable)
+        return f"{name}.pop({args})"
+
+    def _print_ListClear(self, expr):
+        name = self._print(expr.list_variable)
+        return f"{name}.clear()\n"
+
     def _print_Slice(self, expr):
         start = self._print(expr.start) if expr.start else ''
         stop  = self._print(expr.stop)  if expr.stop  else ''
@@ -1143,11 +1152,6 @@ class PythonCodePrinter(CodePrinter):
         annotation = self._print(expr.arg)
         return f'const {annotation}'
 
-    def _print_ListPop(self, expr):
-        args = self._print(expr.pop_index) if expr.pop_index else ""
-        name = self._print(expr.list_variable)
-        return f"{name}.pop({args})"
-
 #==============================================================================
 def pycode(expr, assign_to=None, **settings):
     """ Converts an expr to a string of Python code


Test patch:
diff --git a/tests/epyccel/test_epyccel_lists.py b/tests/epyccel/test_epyccel_lists.py
index f5950364..3b8bb145 100644
--- a/tests/epyccel/test_epyccel_lists.py
+++ b/tests/epyccel/test_epyccel_lists.py
@@ -117,3 +117,40 @@ def test_append_range_tuple(language):
 
     epyc_f = epyccel(f, language=language)
     assert f() == epyc_f()
+
+
+def test_clear_1(language):
+
+    def clear_1():
+        a = [1, 2, 3]
+        a.clear()
+        return a
+
+    epyc_clear_1 = epyccel(clear_1, language = language)
+    pyccel_result = epyc_clear_1()
+    python_result = clear_1()
+    assert python_result == pyccel_result
+
+def test_clear_2(language):
+
+    def clear_2():
+        a = []
+        a.clear()
+        return a
+
+    epyc_clear_2 = epyccel(clear_2, language = language)
+    pyccel_result = epyc_clear_2()
+    python_result = clear_2()
+    assert python_result == pyccel_result
+
+def test_clear_3(language):
+
+    def clear_3():
+        a = [[1, 2, 3]]
+        a.clear()
+        return a
+
+    epyc_clear_3 = epyccel(clear_3, language = language)
+    pyccel_result = epyc_clear_3()
+    python_result = clear_3()
+    assert python_result == pyccel_result