metaclass

Python metaclasses: Why isn't __setattr__ called for attributes set during class definition?

。_饼干妹妹 提交于 2019-11-27 14:51:56
问题 I have the following python code: class FooMeta(type): def __setattr__(self, name, value): print name, value return super(FooMeta, self).__setattr__(name, value) class Foo(object): __metaclass__ = FooMeta FOO = 123 def a(self): pass I would have expected __setattr__ of the meta class being called for both FOO and a . However, it is not called at all. When I assign something to Foo.whatever after the class has been defined the method is called. What's the reason for this behaviour and is there

How to auto register a class when it's defined

一个人想着一个人 提交于 2019-11-27 11:29:31
问题 I want to have an instance of class registered when the class is defined. Ideally the code below would do the trick. registry = {} def register( cls ): registry[cls.__name__] = cls() #problem here return cls @register class MyClass( Base ): def __init__(self): super( MyClass, self ).__init__() Unfortunately, this code generates the error NameError: global name 'MyClass' is not defined . What's going on is at the #problem here line I'm trying to instantiate a MyClass but the decorator hasn't

Using the __call__ method of a metaclass instead of __new__?

我的未来我决定 提交于 2019-11-27 11:07:52
When discussing metaclasses, the docs state: You can of course also override other class methods (or add new methods); for example defining a custom __call__() method in the metaclass allows custom behavior when the class is called, e.g. not always creating a new instance. My questions is: suppose I want to have custom behavior when the class is called, for example caching instead of creating fresh objects. I can do this by overriding the __new__ method of the class. When would I want to define a metaclass with __call__ instead? What does this approach give that isn't achievable with __new__ ?

Triple inheritance causes metaclass conflict… Sometimes

拈花ヽ惹草 提交于 2019-11-27 06:57:54
Looks like I stumbled upon a metaclass hell even when I didn't wanted anything to do with it. I'm writing an app in Qt4 using PySide. I want to separate event-driven part from UI definition, which is generated from Qt Designer files. Hence I create a "controller" classes, but to ease my life I multiple-inherit them anyways. An example: class BaseController(QObject): def setupEvents(self, parent): self.window = parent class MainController(BaseController): pass class MainWindow(QMainWindow, Ui_MainWindow, MainController): def __init__(self, parent=None): super(MainWindow, self).__init__(parent)

python abstractmethod with another baseclass breaks abstract functionality

独自空忆成欢 提交于 2019-11-27 06:06:45
问题 Consider the following code example import abc class ABCtest(abc.ABC): @abc.abstractmethod def foo(self): raise RuntimeError("Abstract method was called, this should be impossible") class ABCtest_B(ABCtest): pass test = ABCtest_B() This correctly raises the error: Traceback (most recent call last): File "/.../test.py", line 10, in <module> test = ABCtest_B() TypeError: Can't instantiate abstract class ABCtest_B with abstract methods foo However when the subclass of ABCtest also inherits from

Metaclass not being called in subclasses

孤人 提交于 2019-11-27 05:57:29
问题 Here is a python session. >>> class Z(type): def __new__(cls, name, bases, attrs): print cls print name return type(name, bases, attrs) ... >>> class Y(object): __metaclass__ = Z ... <class '__main__.Z'> Y >>> class X(Y): ... pass ... >>> class W(Y): ... __metaclass__ = Z ... <class '__main__.Z'> W >>> After I define class X I expect Z._new__ to be called for it, and to print the two line, which is not happening, (as metaclass are inherited?) 回答1: The problem is that the cls argument (which

When should I subclass EnumMeta instead of Enum?

大城市里の小女人 提交于 2019-11-27 05:20:30
In this article Nick Coghlan talks about some of the design decisions that went in to the PEP 435 Enum type , and how EnumMeta can be subclassed to provide a different Enum experience. However, the advice I give (and I am the primary stdlib Enum author) about using a metaclass is it should not be done without a really good reason -- such as not being able to accomplish what you need with a class decorator, or a dedicated function to hide any ugliness; and in my own work I've been able to do whatever I needed simply by using __new__ , __init__ , and/or normal class/instance methods when

__metaclass__ in Python3.5

安稳与你 提交于 2019-11-27 04:52:13
In Python2.7 this code can work very well, __getattr__ in MetaTable will run. But in Python 3.5 it doesn't work. class MetaTable(type): def __getattr__(cls, key): temp = key.split("__") name = temp[0] alias = None if len(temp) > 1: alias = temp[1] return cls(name, alias) class Table(object): __metaclass__ = MetaTable def __init__(self, name, alias=None): self._name = name self._alias = alias d = Table d.student__s But in Python 3.5 I get an attribute error instead: Traceback (most recent call last): File "/Users/wyx/project/python3/sql/dd.py", line 31, in <module> d.student__s AttributeError:

Auto-register class methods using decorator

南笙酒味 提交于 2019-11-27 04:19:23
问题 I want to be able to create a python decorator that automatically "registers" class methods in a global repository (with some properties). Example code: class my_class(object): @register(prop1,prop2) def my_method( arg1,arg2 ): # method code here... @register(prop3,prop4) def my_other_method( arg1,arg2 ): # method code here... I want that when loading is done, somewhere there will be a dict containing: { "my_class.my_method" : ( prop1, prop2 ) "my_class.my_other_method" : ( prop3, prop4 ) }

Error when calling the metaclass bases: function() argument 1 must be code, not str

淺唱寂寞╮ 提交于 2019-11-27 01:44:49
问题 I tried to subclass threading.Condition earlier today but it didn't work out. Here is the output of the Python interpreter when I try to subclass the threading.Condition class: >>> import threading >>> class ThisWontWork(threading.Condition): ... pass ... Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Error when calling the metaclass bases function() argument 1 must be code, not str Can someone explain this error? Thanks! 回答1: You're getting that exception