From bee1c853b8cc3f33a609ef19935234eec425c316 Mon Sep 17 00:00:00 2001 From: Plamen Dimitrov Date: Sat, 16 Apr 2022 18:11:32 +0300 Subject: [PATCH] Implement add() to add cnfvars to cnfvar lists directly from tuples 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 | 24 ++++++++++++++++++++++-- 1 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/cnfvar/model.py b/src/cnfvar/model.py index aff7c38..a8beb5c 100644 --- a/src/cnfvar/model.py +++ b/src/cnfvar/model.py @@ -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) -- 1.7.1