How to fill specific positional arguments with partial in python?

后端 未结 3 1711
悲&欢浪女
悲&欢浪女 2020-12-08 13:18

Basically, what I\'d like to do is:

>>> from functools import partial
>>> partial(str.startswith, prefix=\'a\')(\'a\')
Traceback (most rece         


        
3条回答
  •  春和景丽
    2020-12-08 13:52

    Use this code:

    # See: functoolspartial for binding...
    
    class Function(object):
        def __init__(self, fn):
            self.fn = fn
    
        def __call__(self, *args, **kwargs):
            return self.fn(*args, **kwargs)
    
        def __add__(self, other):
            def subfn(*args, **kwargs):
                return self(*args, **kwargs) + other(*args, **kwargs)
            return subfn
    
    
    class arg(object):
        """Tagging class"""
        def __init__(self, index):
            self.index = index
    
    
    class bind(Function):
        """Reorder positional arguments.
        Eg: g = f('yp', _1, 17, _0, dp=23)
        Then g('a', 'b', another=55) --> f('yp', 'b', 17, 'a', dp=23, another=55)
        """
    
        def __init__(self, fn, *pargs, **pkwargs):
            # Maximum index referred to by the user.
            # Inputs to f above this index will be passed through
            self.fn = fn
            self.pargs = pargs
            self.pkwargs = pkwargs
            self.max_gindex = max(
                (x.index if isinstance(x, arg) else -1 for x in pargs),
                default=-1)
    
        def __call__(self, *gargs, **gkwargs):
            fargs = \
                [gargs[x.index] if isinstance(x, arg) else x for x in self.pargs] + \
                list(gargs[self.max_gindex+1:])
    
            fkwargs = dict(self.pkwargs)
            fkwargs.update(gkwargs)    # Overwrite keys
            return self.fn(*fargs, *fkwargs)
    

    Then try it out like:

    def myfn(a,b,c):
    print(a,b,c)
    
    bind(myfn, arg(1), 17, arg(0))(19,14)
    

提交回复
热议问题