metaclass

Why isn't __instancecheck__ being called?

杀马特。学长 韩版系。学妹 提交于 2019-12-04 08:08:40
I have the following python3 code: class BaseTypeClass(type): def __new__(cls, name, bases, namespace, **kwd): result = type.__new__(cls, name, bases, namespace) print("creating class '{}'".format(name)) return result def __instancecheck__(self, other): print("doing instance check") print(self) print(other) return False class A(metaclass=BaseTypeClass): pass print(type(A)) print(isinstance(A(), A)) and when I run it on Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32 I get the following output creating class 'A' <class '__main__.BaseTypeClass'> True Why

“MetaClass”, “__new__”, “cls” and “super” - what is the mechanism exactly?

六月ゝ 毕业季﹏ 提交于 2019-12-04 07:26:01
问题 I have read posts like these: What is a metaclass in Python? What are your (concrete) use-cases for metaclasses in Python? Python's Super is nifty, but you can't use it But somehow I got confused. Many confusions like: When and why would I have to do something like the following? # Refer link1 return super(MyType, cls).__new__(cls, name, bases, newattrs) or # Refer link2 return super(MetaSingleton, cls).__call__(*args, **kw) or # Refer link2 return type(self.__name__ + other.__name__, (self,

Is it possible to properly copy a class using type

﹥>﹥吖頭↗ 提交于 2019-12-04 07:09:09
According to this answer , a class object cls can be replicated with cls_copy = type('cls_copy', cls.__bases__, dict(cls.__dict__)) This works perfectly for most normal cases. It does not work when the metaclass of cls is not type . My initial naive fix was to do cls_copy = type(cls)('cls_copy', cls.__bases__, dict(cls.__dict__)) However, this is simply pointless. There is no way to know what a metaclass does, as this answer to a related question points out, how it transforms the input dictionary, what additional keywords it requires, etc. The original use of type is almost good enough with a

Python metaclass and the object base class

那年仲夏 提交于 2019-12-04 05:18:24
After reading the excellent SO post , I tried crafting a module level metaclass: def metaclass(future_class_name, future_class_parents, future_class_attrs): print "module.__metaclass__" future_class_attrs["bar"]="bar" return type(future_class_name, future_class_parents, future_class_attrs) __metaclass__=metaclass class Foo(object): def __init__(self): print 'Foo.__init__' f=Foo() This doesn't work (i.e. "module. metaclass " doesn't get printed) unless I remove the object base class of Foo. How come? NOTE: I am using Python 2.6.1. Raymond Hettinger Inheriting from object automatically brings

Can I cast a metaclass object to a protocol type in Swift?

拥有回忆 提交于 2019-12-04 03:40:57
Swift inherited Objective-C's metaclass concept: classes themselves are also considered objects. A class Foo 's object's class is Foo.self , and it is of type Foo.Type . If Foo inherits from Bar , then Foo.self can be assigned to a variable of type Bar.Type , too. This has at least two benefits: it allows to override "static methods"; it's easy to create an instance of an unknown class in a type-safe way and without using reflection. I'm particularly looking at the second one right now. Just to be sure that everybody understands what I'm after, here's an example: class BaseFoo { var

Generic metaclass to keep track of subclasses?

大城市里の小女人 提交于 2019-12-04 02:34:16
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 could invoke it to generate a metaclass for a specific root class with: __metaclass__ = make_subtracker

Sphinx document module properties

陌路散爱 提交于 2019-12-04 01:50:18
I have a module that should have a @property , I solved this by setting a class as the module. I got the idea from this answer: Lazy module variables--can it be done? I wanted this to be repeatable and easy to use so I made a metaclass for it. This works like a charm. The problem is that when using Sphinx to generate documentation properties don't get documented. Everything else is documented as expected. I have no idea how to fix this, maybe this is a problem with Sphinx? The module: import sys import types class ClassAsModule(type): def __new__(cls, name, bases, attrs): # Make sure the name

Adding base class to existing object in python

▼魔方 西西 提交于 2019-12-04 01:20:53
问题 I have several objects of different kinds (different function names, different signatures) and I monkey patch them to have a common way to access them from different functions. Briefly, there is a dispatcher that takes the objects that I want to patch and depending on the object type it calls different patcher. A patcher will add methods to the object: def patcher_of_some_type(object): def target(self, value): # do something and call self methods object.target = types.MethodType(target,

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

落花浮王杯 提交于 2019-12-03 22:04:35
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 mymethod OR for any derived Class. It all seems to work fine until you inherit from something ... say

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

自闭症网瘾萝莉.ら 提交于 2019-12-03 20:07:52
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 the instance is invoked, isn't yet known; and that's the reason for this exercise: discovery). This post