Implement add() to add cnfvars to cnfvar lists directly from tuples
authorPlamen Dimitrov <plamen.dimitrov@intra2net.com>
Sat, 16 Apr 2022 15:11:32 +0000 (18:11 +0300)
committerPlamen Dimitrov <plamen.dimitrov@intra2net.com>
Wed, 11 May 2022 06:25:25 +0000 (09:25 +0300)
The CnfList class already has some functionality for initialization
directly from tuples and the Cnf class already has some functionality
like add_child() for adding a cnfvar from a tuple to Cnf instance's
CnfList instance children. To complete the syntactic sugar circle,
also provide the further possibility to add a CnfList item straight
from a tuple using add() instead of the more raw and manual append()
which can also handle both Cnf instances and tuples similarly to the
previous two options above.

src/cnfvar/model.py

index aff7c38..a8beb5c 100644 (file)
@@ -238,6 +238,27 @@ class BaseCnfList(list):
     def __add__(self, other):
         return CnfList(super().__add__(other))
 
+    def add(self, *args, **kwargs):
+        """
+        Add a CNF variable to the list.
+
+        Arguments can either be a single instance of the :py:class:`Cnf`
+        class or a list of arguments to be passed to the constructor of
+        that class. Similar to the :py:func:`add_child` method for a `Cnf`.
+
+        :returns: the instance that was created
+        :rtype: :py:class:`Cnf`
+        """
+        # support passing a Cnf instance
+        if len(args) == 1 and not kwargs:
+            cnf = args[0]
+            assert isinstance(cnf, Cnf), "A Cnf instance is mandatory with one argument"
+        else:
+            cnf = Cnf(*args, **kwargs)
+
+        self.append(cnf)
+        return cnf
+
 
 class BaseCnf:
     """Base class representing a CNF variable with minimal functionality."""
@@ -335,8 +356,7 @@ class BaseCnf:
         # support passing a Cnf instance
         if len(args) == 1 and not kwargs:
             cnf = args[0]
-            assert isinstance(cnf, Cnf), \
-                   "With one argument, a Cnf instance is mandatory"
+            assert isinstance(cnf, Cnf), "A Cnf instance is mandatory with one argument"
         else:
             cnf = Cnf(*args, **kwargs)