metaclass

Why should I use the __prepare__ method to get a class' namespace?

穿精又带淫゛_ 提交于 2019-12-03 05:59:40
Note This question is not about the Python 3 Enum data type, it's just the example I'm using. With PEP 3115 Python 3 added the __prepare__ 1 method to type for the purpose of allowing a custom namespace to be used when creating classes. For example, the new Enum data type uses __prepare__ to return an instance of the private _EnumDict for use as the new Enum class' namespace. However, I have seen several examples on SO 2 of EnumMeta being subclassed, creating a new namespace for the class in the metaclass __new__ method, but instead of calling the __prepare__ method to acquire that new

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

China☆狼群 提交于 2019-12-03 05:03:25
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 me to do the following MyClassClass = class_factory('spam', 'and', 'eggs') my_instance = MyClassClass(

Understanding metaclass and inheritance in Python [duplicate]

早过忘川 提交于 2019-12-03 02:57:19
问题 This question already has answers here : What are metaclasses in Python? (16 answers) Closed 6 years ago . I have some confusion regarding meta-classes. With inheritance class AttributeInitType(object): def __init__(self,**kwargs): for name, value in kwargs.items(): setattr(self, name, value) class Car(AttributeInitType): def __init__(self,**kwargs): super(Car, self).__init__(**kwargs) @property def description(self): return "%s %s %s %s" % (self.color, self.year, self.make, self.model) c =

Python metaclasses vs class decorators

試著忘記壹切 提交于 2019-12-03 01:10:22
问题 What are the main differences between Python metaclasses and class decorators? Is there something I can do with one but not with the other? 回答1: Decorators are much, much simpler and more limited -- and therefore should be preferred whenever the desired effect can be achieved with either a metaclass or a class decorator. Anything you can do with a class decorator, you can of course do with a custom metaclass (just apply the functionality of the "decorator function", i.e., the one that takes a

Metaclass to parametrize Inheritance

前提是你 提交于 2019-12-03 00:34: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() {} } martineau Although it certainly can be done with metaclasses, you can do what you want without them because in Python

How to pass arguments to the metaclass from the class definition in Python 3.x?

眉间皱痕 提交于 2019-12-02 23:24:04
This is a Python 3.x version of the How to pass arguments to the metaclass from the class definition? question, listed separately by request since the answer is significantly different from Python 2.x. In Python 3.x, how do I pass arguments to a metaclass's __prepare__ , __new__ , and __init__ functions so a class author can give input to the metaclass on how the class should be created? As my use case, I'm using metaclasses to enable automatic registration of classes and their subclasses into PyYAML for loading/saving YAML files. This involves some extra runtime logic not available in PyYAML

Python: Class factory using user input as class names

安稳与你 提交于 2019-12-02 22:24:52
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(myArcher.strength) Unit.strength = 2 print "Strenght ofmyarcher: " + str(myArcher.strength) This leads to

Using metaclasses to override methods of complex builtin

淺唱寂寞╮ 提交于 2019-12-02 21:06:58
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(1.0,1.0) >>> a (1.0,1.0) >>> b = ComplexWrapper(2.0,3.0) >>> b (2.0,3.0) >>> a + b (3+4j) When the

Overriding the default type() metaclass before Python runs

谁说胖子不能爱 提交于 2019-12-02 21:05:23
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 the builtin type() function which is the default metaclass. The new default metaclass will check the test

What is the difference between type and type.__new__ in python?

天涯浪子 提交于 2019-12-02 19:26:00
I was writing a metaclass and accidentally did it like this: class MetaCls(type): def __new__(cls, name, bases, dict): return type(name, bases, dict) ...instead of like this: class MetaCls(type): def __new__(cls, name, bases, dict): return type.__new__(cls, name, bases, dict) What exactly is the difference between these two metaclasses? And more specifically, what caused the first one to not work properly (some classes weren't called into by the metaclass)? In the first example you're creating a whole new class: >>> class MetaA(type): ... def __new__(cls, name, bases, dct): ... print 'MetaA._