python equivalent of functools 'partial' f

2019-02-13 04:34发布

I want to create a class that behaves like collections.defaultdict, without having the usage code specify the factory. EG: instead of

class Config(collections.defaultdict):
    pass

this:

Config = functools.partial(collections.defaultdict, list)

This almost works, but

isinstance(Config(), Config)

fails. I am betting this clue means there are more devious problems deeper in also. So is there a way to actually achieve this?

I also tried:

class Config(Object):
    __init__ = functools.partial(collections.defaultdict, list)

2条回答
一夜七次
2楼-- · 2019-02-13 05:09

I don't think there's a standard method to do it, but if you need it often, you can just put together your own small function:

import functools
import collections


def partialclass(cls, *args, **kwds):

    class NewCls(cls):
        __init__ = functools.partialmethod(cls.__init__, *args, **kwds)

    return NewCls


if __name__ == '__main__':
    Config = partialclass(collections.defaultdict, list)
    assert isinstance(Config(), Config)
查看更多
来,给爷笑一个
3楼-- · 2019-02-13 05:21

If you actually need working explicit type checks via isinstance, you can simply create a not too trivial subclass:

class Config(collections.defaultdict):

    def __init__(self): # no arguments here
        # call the defaultdict init with the list factory
        super(Config, self).__init__(list)

You'll have no-argument construction with the list factory and

isinstance(Config(), Config)

will work as well.

查看更多
登录 后发表回答