metaclass

How to pass arguments to the metaclass from the class definition?

☆樱花仙子☆ 提交于 2019-12-03 15:17:35
问题 I'm trying to dynamically generate classes in python 2.7, and am wondering if you can easily pass arguments to the metaclass from the class object. I've read this post, which is awesome, but doesn't quite answer the question. at the moment I am doing: def class_factory(args, to, meta_class): Class MyMetaClass(type): def __new__(cls, class_name, parents, attrs): attrs['args'] = args attrs['to'] = to attrs['eggs'] = meta_class class MyClass(object): metaclass = MyMetaClass ... but this requires

Subclassed django models with integrated querysets

二次信任 提交于 2019-12-03 13:13:40
Like in this question , except I want to be able to have querysets that return a mixed body of objects: >>> Product.objects.all() [<SimpleProduct: ...>, <OtherProduct: ...>, <BlueProduct: ...>, ...] I figured out that I can't just set Product.Meta.abstract to true or otherwise just OR together querysets of differing objects. Fine, but these are all subclasses of a common class, so if I leave their superclass as non-abstract I should be happy, so long as I can get its manager to return objects of the proper class. The query code in django does its thing, and just makes calls to Product().

Who calls the metaclass

僤鯓⒐⒋嵵緔 提交于 2019-12-03 12:33:08
This actually stems from a discussion here on SO. Short version def meta(name, bases, class_dict) return type(name, bases, class_dict) class Klass(object): __metaclass__ = meta meta() is called when Klass class declaration is executed. Which part of the (python internal) code actually calls meta() ? Long version When the class is declared, some code has to do the appropriate attribute checks and see if there is a __metaclass__ declared on a type. If such exists, it has to perform a method call on that metaclass with the well known (class_name, bases, class_dict) attributes. It is not really

Metaclass to parametrize Inheritance

点点圈 提交于 2019-12-03 11:04:28
问题 I've read some tutorials on Python metaclasses. I've never used one before, but I need one for something relatively simple and all the tutorials seem geared towards much more complex use cases. I basically want to create a template class that has some pre-specified body, but takes its base class as a parameter. Since I got the idea from C++/D templates, here's an example of what the code I want to write would look like in C++: template<class T> class Foo : T { void fun() {} } 回答1: Although it

When to inline definitions of metaclass in Python?

柔情痞子 提交于 2019-12-03 10:27:10
Today I have come across a surprising definition of a metaclass in Python here , with the metaclass definition effectively inlined. The relevant part is class Plugin(object): class __metaclass__(type): def __init__(cls, name, bases, dict): type.__init__(name, bases, dict) registry.append((name, cls)) When does it make sense to use such an inline definition? Further Arguments: An argument one way would be that the created metaclass is not reusable elsewhere using this technique. A counter argument is that a common pattern in using metaclasses is defining a metaclass and using it in one class

Why does the class definition's metaclass keyword argument accept a callable?

我是研究僧i 提交于 2019-12-03 07:55:19
Background The Python 3 documentation clearly describes how the metaclass of a class is determined: if no bases and no explicit metaclass are given, then type() is used if an explicit metaclass is given and it is not an instance of type(), then it is used directly as the metaclass if an instance of type() is given as the explicit metaclass, or bases are defined, then the most derived metaclass is used Therefore, according to the second rule, it is possible to specify a metaclass using a callable. E.g., class MyMetaclass(type): pass def metaclass_callable(name, bases, namespace): print("Called

Overriding the default type() metaclass before Python runs

和自甴很熟 提交于 2019-12-03 07:40:10
问题 Here be dragons. You've been warned. I'm thinking about creating a new library that will attempt to help write a better test suite. In order to do that one of the features is a feature that verifies that any object that is being used which isn't the test runner and the system under test has a test double (a mock object, a stub, a fake or a dummy). If the tester wants the live object and thus reduce test isolation it has to specify so explicitly. The only way I see to do this is to override

Using metaclasses to override methods of complex builtin

非 Y 不嫁゛ 提交于 2019-12-03 07:37:57
问题 As a learning exercise, I'm trying to implement a class which will emulate the behavior of python's complex builtin, but with different behavior of the __str__ and __repr__ methods: I want them to print in the format... (1.0,2.0) ...instead of: (1+2j) I first tried simply subclassing from complex and redefining __str__ and __repr__ , but this has the problem that when non-overridden methods are called, a standard complex is returned, and printed in the standard format: >>> a = ComplexWrapper

Python: Class factory using user input as class names

Deadly 提交于 2019-12-03 07:32:45
问题 I want to add class atttributes to a superclass dynamically. Furthermore, I want to create classes that inherit from this superclass dynamically, and the name of those subclasses should depend on user input. There is a superclass "Unit", to which I can add attributes at runtime. This already works. def add_attr (cls, name, value): setattr(cls, name, value) class Unit(object): pass class Archer(Unit): pass myArcher = Archer() add_attr(Unit, 'strength', 5) print "Strenght ofmyarcher: " + str

Body of abstract method in Python 3.5 [duplicate]

断了今生、忘了曾经 提交于 2019-12-03 06:11:27
This question already has an answer here : What should I put in the body of an abstract method in Python (1 answer) I have an abstract class, Model , with a few abstract methods, what should I put in the body of the methods? A return class Model(metaclass=ABCMeta): @abstractmethod def foo(self): return A pass class Model(metaclass=ABCMeta): @abstractmethod def foo(self): pass Raising a descriptive error class Model(metaclass=ABCMeta): @abstractmethod def foo(self): raise NotImplementedError("Class {class_name} doesn't implement {func_name} function" .format(class_name=self.__class__.__name__,