indirect **keyword calls

Terry Hancock hancock at anansispaceworks.com
Mon Oct 28 03:59:11 EST 2002


Hi all,
I've just recently come across a need for this idiom (isn't
this new in Python 2.x?):

def my_func(spam, ham=1, **eggs):
     #...
     pass

where 'eggs' gets a dictionary of keyword arguments.  I
haven't previously had any experience with it.

It seems that Zope's ZSQL methods accept their arguments
in this form, but I need to provide an intermediate layer.
Is there any way of writing a general call that passes a
received set of keywords on to a called function.  The
following is apparently illegal, but I hope it expresses the
concept:

def sql_funct_i_want_to_call(**kw):
    """
    makes an SQL query using keyword args and returns
    a result object, kw always contains a "username=''"
    field in this case.
    """
    # ...
    pass

def my_wrapper(username='anonymous', **kw):
    """
    Now I want to try the call and return the result
    if there is one. Otherwise, I want to return a default
    record.
    """
    kw['username']=username
    result = sql_funct_i_want_to_call(kw)
    if result:
        return result
    else:
        kw['username']='anonymous'
        result = sql_funct_i_want_to_call(kw)
        if not result:
            raise BrokenDBError("Database has no anonymous/default user")
        else:
            return result

Or something along those lines. The only problem is that python
doesn't seem to understand what I want when I try to pass the
dictionary to the object
"TypeError: sql_funct_i_want_to_call() takes exactly 0 arguments (1 given)"

Is there a way to get what I want to do here without having
to go through too many hoops?  If I knew in advance what
the arguments would be, I could do it that way, but I'd like to
be able to define a general behavior and use it for a lot of
similar SQL calls, in which case, kw would vary depending on
the call needed.

Maybe this is really obvious to someone else, but I can't see how
to do it.

Thanks for any ideas,
Terry

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com




More information about the Python-list mailing list