metaclass

Override Python metaclass __getitem__

你。 提交于 2021-02-11 06:29:29
问题 Given the following code, I expect a return value of 'overridden' not 'value1' : class MyMetaclass(type): def __new__(cls, name, bases, attrs): attrs.update({'_my_dict': {'key1': 'value1', 'key2': 'value2'}}) return super().__new__(cls, name, bases, attrs) def __getitem__(cls, value): return cls._my_dict[str(value)] class MyBaseClass(metaclass=MyMetaclass): pass class MyClass(MyBaseClass): @classmethod def __getitem__(cls, value): return 'overridden' >>> MyClass['key1'] 'value1' # I expect:

__classcell__ generates error in Python 3.6 when the metaclass calls multiple super().__new__ from inherited class

送分小仙女□ 提交于 2021-02-10 14:39:16
问题 Here is an executable code which works in Python 2.7 but results in an error in Python 3.6: import six class AMeta(type): def __new__(cls, name, bases, attrs): module = attrs.pop('__module__') new_attrs = {'__module__': module} classcell = attrs.pop('__classcell__', None) if classcell is not None: new_attrs['__classcell__'] = classcell new = super(AMeta, cls).__new__( cls, name, bases, new_attrs) new.duplicate = False legacy = super(AMeta, cls).__new__( cls, 'Legacy' + name, (new,), new_attrs

Python dynamic properties and mypy

跟風遠走 提交于 2021-02-08 15:17:36
问题 I'm trying to mask some functions as properties (through a wrapper which is not important here) and add them to the object dynamically, however, I need code completion and mypy to work. I figured out how to add a property dynamically (either through a metaclass or simply in constructor), but the problem I have is mypy doesn't pick it up (and neither does the IDE). One workaround is to define an attribute with the same name/type, but I really don't like this approach (too much code, static set

Python dynamic properties and mypy

自闭症网瘾萝莉.ら 提交于 2021-02-08 15:17:05
问题 I'm trying to mask some functions as properties (through a wrapper which is not important here) and add them to the object dynamically, however, I need code completion and mypy to work. I figured out how to add a property dynamically (either through a metaclass or simply in constructor), but the problem I have is mypy doesn't pick it up (and neither does the IDE). One workaround is to define an attribute with the same name/type, but I really don't like this approach (too much code, static set

Python extension in C - Metaclass

被刻印的时光 ゝ 提交于 2021-02-08 10:21:06
问题 I have the following python code: class Meta(type): def __call__(cls, *args, **kwargs): obj = type.__call__(cls, *args, **kwargs) # Only do checks for subclasses if cls.__name__ == 'Parent': return obj required_attrs = ['x'] for ra in required_attrs: if ra not in dir(obj): fmt = 'Subclasses of Parent must define the %s attribute' raise NotImplementedError(fmt % ra) return obj class Parent(metaclass=Meta): pass class Child(Parent): def __init__(self): self.x = True Meta is used only to require

Python extension in C - Metaclass

佐手、 提交于 2021-02-08 10:19:42
问题 I have the following python code: class Meta(type): def __call__(cls, *args, **kwargs): obj = type.__call__(cls, *args, **kwargs) # Only do checks for subclasses if cls.__name__ == 'Parent': return obj required_attrs = ['x'] for ra in required_attrs: if ra not in dir(obj): fmt = 'Subclasses of Parent must define the %s attribute' raise NotImplementedError(fmt % ra) return obj class Parent(metaclass=Meta): pass class Child(Parent): def __init__(self): self.x = True Meta is used only to require

Change type of an object after its creation (typecasting in Python)

…衆ロ難τιáo~ 提交于 2021-02-08 02:11:14
问题 In my project, I generate an object obj of type CubicObject . At runtime, a GUI setting should be allowed to change the type of obj to Tofu or Box (and back), depending on what the user wants to do and what (s)he thinks the object is best represented by. Then the user should benefit from specific algorithms implemented in the corresponding classes. I am looking for a nice implementation of this behaviour. I have played with the code below, which changes the __class__ attribute, but I am sure

Python class inherited singleton inits instance on every call

这一生的挚爱 提交于 2021-01-29 12:26:33
问题 I'm trying to implement class inherited singleton as described here (Method 2). Going over the question and the extensive chosen answer I tried to implement the following: class Singleton(object): _instance = None def __new__(cls, *args, **kwargs): if not isinstance(cls._instance, cls): cls._instance = object.__new__(cls, *args, **kwargs) cls._instance._initialized = False return cls._instance class A(Singleton): def __init__(self): print "Init is called" class B(Singleton): def __init__(self

Python metaclass - make class property accessible via class and class instance

大兔子大兔子 提交于 2021-01-27 06:58:51
问题 Using python 3.7, I have created a class property in a metaclass. I would like to be able to access the property via the class itself or an instantiated object of the class. I can emulate it by creating a class property AND an instance property, but it screws with PyCharm's type hinting. Here's what I consider the ideal set up: class Meta(type): @property def cls_prop(cls) -> str: return 'foo' class A(metaclass=Meta): pass But unfortunately, here are the results: >>> A.cls_prop 'foo' >>> a =

Python metaclass - make class property accessible via class and class instance

余生颓废 提交于 2021-01-27 06:55:35
问题 Using python 3.7, I have created a class property in a metaclass. I would like to be able to access the property via the class itself or an instantiated object of the class. I can emulate it by creating a class property AND an instance property, but it screws with PyCharm's type hinting. Here's what I consider the ideal set up: class Meta(type): @property def cls_prop(cls) -> str: return 'foo' class A(metaclass=Meta): pass But unfortunately, here are the results: >>> A.cls_prop 'foo' >>> a =