metaclass

Generic metaclass to keep track of subclasses?

人走茶凉 提交于 2019-12-05 15:19:27
问题 I'm trying to writing a generic metaclass for tracking subclasses Since I want this to be generic, I didn't want to hardcode any class name within this metaclass, therefore I came up with a function that generates the proper metaclass, something like: def make_subtracker(root): class SubclassTracker(type): def __init__(cls, name, bases, dct): print('registering %s' % (name,)) root._registry.append(cls) super(SubclassTracker, cls).__init__(name, bases, dct) return SubclassTracker This way I

Setting metaclass of wrapped class with Boost.Python

霸气de小男生 提交于 2019-12-05 10:16:34
I have an Event class defined in C++ that I expose to Python using Boost. My scripts are expected to derive from this class, and I'd like to do some initialization whenever a new child class is defined. How can I set the metaclass of the exposed Event class such that whenever a Python script derives from this class, the metaclass could do the required initialization? I would like to avoid having to explicitly use a metaclass in the scripts... class KeyboardEvent(Event): # This is what I want pass class KeyboardEvent(Event, metaclass=EventMeta): # This is not a good solution pass Edit: Part of

Metaclasses and when/how functions are called

不羁岁月 提交于 2019-12-05 09:59:52
问题 I'm trying to learn how metaclasses work in python 3. Things I want to know are: which functions are called, in what order, and their signatures and returns. As an example, I know __prepare__ gets called when a class with a metaclass is instantiated with arguments metaclass, name_of_subclass, bases and returns a dictionary representing the future namespace of the instantiated object. I feel like I understand __prepare__ 's step in the process well. What I don't, though, are __init__ , __new__

Sqlalchemy dynamically create table and mapped class

有些话、适合烂在心里 提交于 2019-12-05 07:58:25
问题 Given a set of column names and their types, the goal is to to instantiate a table and the corresponding mapped class. It is related to question posted here: Dynamic Class Creation in SQLAlchemy. So far I have the following: table = Table(tbl, metadata, *(Column(col, ctype, primary_key=pk, index=idx) for col, ctype, pk, idx in zip(attrs, types, primary_keys, indexes)) ) This creates the table object. Now I need to create the corresponding class. mydict={'__tablename__':tbl} cls = type(cls

Why Groovy's map does not have metaClass?

柔情痞子 提交于 2019-12-05 05:29:58
Why does Groovy's literal map does not have a metaClass? // lists work as expected: aList = [] println aList.class // class java.util.ArrayList println aList.metaClass // gives the full blown metaclass // org.codehaus.groovy.runtime.HandleMetaClass@3de6696c // [groovy.lang.MetaClassImpl@3de6696c[class java.util.ArrayList]] // string and numbers too: println ''.metaClass println 12.metaClass // map does not: aMap = [:] println myMap.metaClass // gives null println myMap.class // also gives null Tested with: Groovy Version: 1.8.6 JVM: 1.6.0_31 Vendor: Sun Microsystems Inc. OS: Linux You have to

Wrapping all possible method calls of a class in a try/except block

点点圈 提交于 2019-12-05 04:33:16
问题 I'm trying to wrap all methods of an existing Class (not of my creation) into a try/except suite. It could be any Class, but I'll use the pandas.DataFrame class here as a practical example. So if the invoked method succeeds, we simply move on. But if it should generate an exception, it is appended to a list for later inspection/discovery (although the below example just issues a print statement for simplicity). (Note that the kinds of data-related exceptions that can occur when a method on

Why doesn't the abc.ABCMeta abstract instantiation check work on derivatives of `list` and `dict`?

帅比萌擦擦* 提交于 2019-12-05 04:01:12
问题 I have been experimenting a little with the abc module in python. A la >>> import abc In the normal case you expect your ABC class to not be instantiated if it contains an unimplemented abstractmethod . You know like as follows: >>> class MyClass(metaclass=abc.ABCMeta): ... @abc.abstractmethod ... def mymethod(self): ... return -1 ... >>> MyClass() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Can't instantiate abstract class MyClass with abstract methods

How to convert a string with the name of a class to the class type itself?

纵然是瞬间 提交于 2019-12-05 03:25:52
In order to store a class name in a log file I converted the description of a class type to a string: let objectType: NSObject.Type = Object.self let str = String(describing: objectType) However, I do not succeed in back conversion of str to a variable of type NSObject.Type to use it in a generic method. How could I do this? You can get your class back from string , but you need to use your project's module name while getting class name. If you don't use your module name then it will return nil because the class name you have referenced earlier is not fully qualified by the module name . You

Custom metaclass to create hybrid properties in SQLAlchemy

霸气de小男生 提交于 2019-12-04 17:41:25
I want to create a custom interface on top of SQLAlchemy so that some pre-defined hybrid properties are supported transparently. Specifically, I want to create a class SpecialColumn and a metaclass so that when a user adds SpecialColumn as an attribute of a class, my custom metaclass replaces that attribute with two SQLAlchemy Column s and adds a hybrid property that gets and sets those two columns as a tuple. Here's my approach so far: First, I defined my special column type: class SpecialColumn(object): pass Then, I defined a metaclass inheriting from DeclarativeMeta which scans the class

TypeErrors using metaclasses in conjunction with multiple inheritance

三世轮回 提交于 2019-12-04 10:01:01
I have two questions converning metaclasses and multiple inheritance. The first is: Why do I get a TypeError for the class Derived but not for Derived2 ? class Metaclass(type): pass class Klass(object): __metaclass__ = Metaclass #class Derived(object, Klass): pass # if I uncomment this, I get a TypeError class OtherClass(object): pass class Derived2(OtherClass, Klass): pass # I do not get a TypeError for this The exact error message is: TypeError: Error when calling the metaclass bases Cannot create a consistent method resolution order (MRO) for bases object, Klass The second question is: Why