On Mon, Mar 24, 2008 at 6:19 AM, Julien <[EMAIL PROTECTED]> wrote:
>  I would like to do something like:
>
>  def called(arg)
>     if arg==True:
>         !!magic!!caller.return 1
>
>  def caller(arg)
>     called(arg)
>     return 2
>


"called" look like a precondition constrain[1], then It will be nice
to program these features adding this paradigm to python. Next is just
an very reduced example:

<code>
#!/usr/bin/python

class PreconditionViolationError(AssertionError): pass

def requires(predicate, help=None):
    'Pre-condition as in http://en.wikipedia.org/wiki/Design_by_contract'
    def decorator(wrapped):
        def wrapper(*args, **kwds):
            if predicate(*args, **kwds):
                return wrapped(*args, **kwds)
            else:
                aux = help or predicate.__doc__ or wrapper.__doc__
                raise PreconditionViolationError, "%s, (%s)" %
(wrapper.__name__, help)
        # return update_wrapper(wrapper, wrapped)   # Requires Python 2.5
        return wrapper
    return decorator


def validate(called):
    'Special pre-condition to return a value'
    def decorator(wrapped):
        def wrapper(*args, **kwds):
            try:
                return called(*args, **kwds)
            except:
                return wrapped(*args, **kwds)
        return wrapper
    return decorator

def called(arg):
    if arg:
        return 1
    else:
        raise PreconditionViolationError, "False arg"

@validate(called)
def caller(arg):
    return 2

if __name__ == '__main__':
    print 'OK: %s' % caller(True)
    print 'NOT OK: %s' % caller(False)
</code>

I included a real-precondition I use in my programs. "validate" is a
metaphor for the sake of this example, to answer the Julien's question
my way.

Regards

[1] http://en.wikipedia.org/wiki/Design_by_contract

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to