Best way to ensure user calls methods in correct order?

Thomas Nyberg tomuxiong at gmx.com
Thu Jun 22 11:35:36 EDT 2017


[I accidentally sent this only to Peter, but wanted instead to send it
to the list for anyone else who happens upon it...now sending to the
list...]

On 06/22/2017 04:31 PM, Peter Otten wrote:
> If the order is linear like it seems to be the following might work:

Thanks a lot! This removes the duplication that was bothering me. To get
the error messages I wanted, I changed the code minorly as follows:

------------------------------------------
import itertools


class ConsistencyError(Exception):
    pass


class InOrder:
    def __init__(self):
        self.indices = itertools.count(1)
        self.prior_method_name = ""

    def __call__(self, method):
        index = next(self.indices)
        prior_method_name = self.prior_method_name
        method_name = method.__name__
        self.prior_method_name = method_name

        def wrapper(this, *args, **kw):
            if index - this.state > 1:
                msg = "call {}() before calling {}()".format(
                    prior_method_name, method_name)
                raise ConsistencyError(msg)
            result = method(this, *args, **kw)
            this.state = index
            return result

        return wrapper


class C:
    def __init__(self):
        self.state = 0

    inorder = InOrder()

    @inorder
    def a(self):
        print("Calling a()...")

    @inorder
    def b(self):
        print("Calling b()...")

    @inorder
    def c(self):
        print("Calling c()...")

    @inorder
    def d(self):
        print("Calling d()...")
------------------------------------------

Now of course I'll have to consider Steve's response and wonder _why_
exactly I'm doing this...

Cheers,
Thomas



More information about the Python-list mailing list