JungYT
JungYT

Reputation: 1

How to change the order of function's argumnets

*edited

What I want to is as below

def func(x1, x2, ... , xi, ..., xn):
   doing something
   return

def F(func, i):
   def newFunc(xi, x2, ..., x1, ..., xn):
      return func(x1, x2, ..., xi, ..., xn)
   doing something with newFunc

where n is unknown(arbitrary) *

I am not good at English and I am a beginner of python, so please understand. I make a function that takes a function and an integer. Let me call the function what I make as F, the function that is an argument of F as func, and the integer as i. In the F, a new function which first argument and i-th argument of func are switched is made. (I'll do something with the new function in F.) If I exactly know the arguments of func, I can make the F as below. But If I don't know the number of arguments, how can I make F?

def F(func, i=1):
    def newFunc(u, x, e):
        return func(x, u, e)

    ...Do something with newFunction...

I tried signature, but the return of signature can't be switched. And I tried .__code__.co_varnames as below

def F(func, i):
    arg_num = func.__code__.co_argcount
    arg_pre = list(func.__code__.co_varnames)[:arg_num]
    arg_next = list(func.__code__.co_varnames)[:arg_num]
    arg_next[0], arg_next[i] = arg_next[i], arg_next[0]
    def newFunc(arg_next):
        return func(arg_pre)

In this case, however, return func(arg_pre) recognizes arg_pre as 1 positional argument.

I hope you understand what I want to mean. Thank you.

Upvotes: 0

Views: 67

Answers (1)

chepner
chepner

Reputation: 531055

newFunc can accept an arbitrary number of arguments, although this means F cannot verify that there really is an ith argument when you call the return value of F.

def F(func, i=1):
    def newFunc(*args):
        x = args[0]
        y = args[i]
        return func(y, *args[1:i], x, *args[i+1:])
    return newFunc

Upvotes: 1

Related Questions