简体   繁体   中英

A way to automatically pass parameters to a function?

I have a bunch of callback functions in a module. They all call some_func() with the first, say, couple of arguments always the same and derived from their own arguments, while other arguments vary. Like so:

from outer.space import some_func
def callback_A(param1, param2, param3):
    ...
    some_func(param2+param1, param3, ..., ...)
    ...

def callback_B(param1, param2, param3, param4):
    ...
    some_func(param2+param1, param3, ..., ...)
    ...

And it's all over the code. And uglier than just param2+param1.

In C/C++, I'd just do a macro

#define    S_F(a,b)    some_func(param2+param1, param3, a, b)

and start using S_F inside callbacks instead of some_func . What can I do in Python?

You can use functools.partial

>>> from functools import partial
>>> def my_function(a,b,c,d,e):
...     print (a,b,c,d,e)
... 
>>> func_with_defaults = partial(my_function, 1, 2, e=5)
>>> func_with_defaults(3, 4)
(1, 2, 3, 4, 5)

Edit:

Since you do not have these values in advance you can't use partial or lambda . You may be tempted to do this:

>>> A = lambda x: x + y
>>> def do_something(y):
...     return A(2)    # hope it uses the `y` parameter...
... 
>>> do_something(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in do_something
  File "<stdin>", line 1, in <lambda>
NameError: global name 'y' is not defined

But as can you see it does not work. Why? Because when you define a function python saves the scope in which you defined it and uses it to resolve the global / nonlocal variables.

If you had access to some_func it would be possible to do what you want by "hacking" the interpreter stack using inspect but this is not a robust nor elegant thing to do, so do not do that.

What I'd do in your case is to simply rewrite the statement.

If you really want to avoid this, you can try something using exec :

>>> def some_function(a,b,c):
...     print(a,b,c)
... 
>>> code = 'some_function(a+b,c,%s)'
>>> 
>>> def func_one(a,b, c):
...     exec code % 1
... 
>>> def func_two(a,b,c):
...     exec code % 2
... 
>>> func_one(1,2,3)
(3, 3, 1)
>>> func_two(1,2,3)
(3, 3, 2)

But this is ugly .

If you use only positional arguments to your function you may do something more elegant such as:

>>> def compute_values(a,b,c):
...     return (a+b, c)
... 
>>> def func_one(a,b,c):
...     some_function(*(compute_values(a,b,c) + (1,)))
... 
>>> def func_two(a,b,c):
...     some_function(*(compute_values(a,b,c) + (2,)))
... 
>>> func_one(1,2,3)
(3, 3, 1)
>>> func_two(1,2,3)
(3, 3, 2)

But at this point you are just repeating a different text, and you lost much readability. If you want to have preprocessing features in python you may try Python Preprocessing , even though, in your case, I'd rather just repeat the function calls.

You could base it on decorators:

import functools
from outer.space import some_func

def with_some(f):
    @functools.wraps(f)
    def wrapper(param1, param2, param3, *args):
        new_args = f(*args)
        return some_func(param1+param2, param3, *new_args)

    return wrapper

@with_some
def callback_A():
    return ()  # Will call some_func(param1 + param2, param3)

...

@with_some
def callback_B(param4):
    return param4,  # some_func(param1 + param2, param3, param4)

The wrapped functions will all have signature f(param1, param2, param3, *args)

S_F = lambda a, b: some_func(param2+params1, param3, a, b)

请记住, param1param2param3必须在 lambda 语句的范围内可用,就像some_func

How about with keyword arguments instead of positional arguments in the function signature:

some_func(**kwargs):
    Instead of position arguments, just use the keys that some_func can respond to. 
    You can defaults to the ones not included...
    if key1 in kwargs:
        #use key1...
    #...

def callback_A(param1, param2, param3):
    some_func(key1=param1+parma2,key2=param3, other_key=...)


def callback_B(param1, param2, param3, param4):
     some_func(key1=param2+param1, key2=param3, other_keys=..., ...)

Edit

If you cannot change the function signature to some_func then you can wrap it:

def some_func(a,b,c,d,e):
    print 'some_funct({}, {}, {}, {}, {})'.format(a,b,c,d,e)

def some_func_wrap(**kwargs):
    params={'p1':'default a','p2':'default b',
              'p3':'default c','p4':'default d','p5':'default e'}
    for p,arg in kwargs.items():
        try:
            del params[p]   # to raise an error if bad key
            params[p]=arg
        except KeyError:
            print 'bad param to some_func_wrap()\n'
            raise

    some_func(*[params[k] for k in sorted(params.keys())])

some_func_wrap(p1=1,p2=1+3)

prints: some_funct(1, 4, default c, default d, default e)

Simplely you can just use globals()/locals() to automatically get the context variables.

But if your functions saved in different files, then you can try inspect module to access caller's variables.

import inspect

def f1():
    v=11111
    f2()

def f2():
    v = inspect.stack()[1][0].f_locals['v']
    print(v)

f1() # print 11111

Here is another similar question: Access variables of caller function in Python

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM