Monday, 15 June 2015

python - Can functools.partial be used to bind arbitrary positional arguments? -


Suppose you define partial to set positional arguments in an arbitrary order To correct 2 and 3 th arguments you want, the results you want to apply partial to str.split are as follows:

  Lambda: str.rsplit (S, SEP, 1) #Sep was given.   

(I use s.rsplit (... instead of str.rsplit (s ... and To make more points)

  partial (str.rsplit, sep = SEP, maxsplit = 1) #         SEP   

but str.rsplit does not use keyword logic, only positional.

Partially, how to fix those arguments? The only option is long and wrapper?

If you want to define the function inline, then the rapper is ugly, like the function's Defining the argument for the dispute. Lambda is Defacto here, and partial is the second option, but in this case it is lacking. You can not do this with the partial . This is because The PyArg_ParseTuple function uses the API that does not provide keyword logic from split . From Python's perspective, it seems that the method is defined as Interpretation:

  DEF division (self, * Arges): If Len (Arjis) & gt; 2: Increase the type arrow (...) sep = args [0] if the args and none maxsplit = args [1] if LAN (Args)> gt; 1 and -1 ...   

Can only provide positional logic in partial order. It is mentioned, where they say that partial "is almost equivalent":

  def partial (func, * args, ** keywords): def newfunc (* Fargs, ** fkeywords): newkeywords = keywords.copy () newkeywords.update (fkeywords) return func (* (args + fargs), ** newkeywords) newfunc.func = func newfunc.args = args newfunc.keywords = keyword newfunc   

Note return func (* (args + fargs), ** newkeywords) which clearly shows that you partial Other functions are included in Arguments.

The conclusion is that lambda is more powerful than partial .

On the one hand, in Python 3.3, you can specify maxsplit as a keyword argument:

  & gt; & Gt; & Gt; '' Some strings with spaces ''. (Same as 'max', 'some', 'string', 'empty space']   

and this was also the same issue for many other methods / functions.

No comments:

Post a Comment