Possible PEP: Improve classmethod/staticmethod syntax

Michael Chermside mcherm at mcherm.com
Wed Jun 4 17:46:51 CEST 2003

  [... discussion of descriptor syntax for pre/post conditions ...]

> For the pre- and post-condition stuff this works well.  To
> use lists there you have to extend list constructor syntax somehow, as I
> used in my original message:
>     def foo(...) [pre=foo_pre, post=foo_post]:
>         <normal code here>
> You could also use strings:
>     def foo(...) ['pre=foo_pre', 'post=foo_post']:
>         <normal code here>

I don't think either awkward workaround is necessary. It seems to me
that you could use something like this:

    def foo(...) [precondition(foo_pre), postcondition(foo_post)]:
        <normal code here>

Notice that precondition and postcondition are functions that take
in one function as an argument and give out a function which can be
applied to foo to give foo-prime. Yes, that's abstract, but it's
not as hard to code as it is to talk about. Here's a simple example
which lacks many of the features you'd like in a DBC system but
illustrates what I mean:

    # WARNING: Untested code
    def precondition(tests):
        def decorator(foo):
            def fooPrime(*args, **kwargs):
                if tests(*args, **kwargs):
                    return foo(*args, **kwargs)
                    raise PreconditionFailure()
            return fooPrime
        return decorator

The level of abstraction here is a far less serious issue than
the need to invent new syntax or the loss of order for the
decorators. Particularly so because precondition and postcondition
would be like classmethod and staticmethod... provided so that
you don't have to write them yourself!

-- Michael Chermside

More information about the Python-list mailing list