python equivalent of functools partial for a class / constructor

2024/11/20 6:24:04

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)
Answer

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 collectionsdef partialclass(cls, *args, **kwds):class NewCls(cls):__init__ = functools.partialmethod(cls.__init__, *args, **kwds)return NewClsif __name__ == '__main__':Config = partialclass(collections.defaultdict, list)assert isinstance(Config(), Config)
https://en.xdnf.cn/q/26354.html

Related Q&A

Set the font size in pycharms python console or terminal

There are terminal and python console in pycharm, which are very convenient. But I found that the font size was too small to recognize in terminal or python console. How can change the font size in the…

How to filter model results for multiple values for a many to many field in django

I have the following Model:class Group(models.Model):member = models.ManyToManyField(Player, through=GroupMember)name = models.CharField(max_length=20, unique=True)join_password = models.CharField(max_…

Why is string comparison so fast in python?

I became curious to understand the internals of how string comparison works in python when I was solving the following example algorithm problem:Given two strings, return the length of the longest comm…

What is a namespace object?

import argparseparser = argparse.ArgumentParser(description=sort given numbers) parser.add_argument(-s, nargs = +, type = int) args = parser.parse_args() print(args)On command line when I run the comma…

How to get the element-wise mean of an ndarray

Id like to calculate element-wise average of numpy ndarray.In [56]: a = np.array([10, 20, 30])In [57]: b = np.array([30, 20, 20])In [58]: c = np.array([50, 20, 40])What I want:[30, 20, 30]Is there any …

Spark 1.4 increase maxResultSize memory

I am using Spark 1.4 for my research and struggling with the memory settings. My machine has 16GB of memory so no problem there since the size of my file is only 300MB. Although, when I try to convert …

Java abstract/interface design in Python

I have a number of classes which all share the same methods, only with different implementations. In Java, it would make sense to have each of these classes implement an interface or extend an abstract…

PyCharm - no tests were found?

Ive been getting na error in PyCharm and I cant figure out why Im getting it:No tests were foundThis is what I have for my point_test.py: import unittest import sys import ossys.path.insert(0, os.path.…

Does Python PIL resize maintain the aspect ratio?

Does PIL resize to the exact dimensions I give it no matter what? Or will it try to keep the aspect ratio if I give it something like the Image.ANTIALIAS argument?

How to scale images to screen size in Pygame

I was wondering how I would go about scaling the size of images in pygame projects to the resolution of the screen. For example, envisage the following scenario assuming windowed display mode for the t…