Having searched for a way to enforce immutability of custom types and not having found a satisfactory answer I came up with my own shot at a solution in form of a metaclass:
class ImmutableTypeException( Exception ): pass
class Immutable( type ):
'''
Enforce some aspects of the immutability contract for new-style classes:
- a...
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...
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 b...
Hello,
for putting methods of various classes into a global registry I'm using a decorator with a metaclass. The decorator tags, the metaclass puts the function in the registry:
class ExposedMethod (object):
def __init__(self, decoratedFunction):
self._decoratedFunction = decoratedFunction
def __call__(__self,*__args,*...
I've been starting to learn Groovy and am currently looking at the metaclass functionality. I have seen the examples of adding a new method, and removing all methods, but nothing about removing a single method. For example:
String.metaClass.foo = {delegate.toUpperCase()}
String.metaClass.bar = {delegate.toLowerCase()}
with the obvious...
Groovy adds each() and a number of other methods to java.lang.Object. I can't figure out how to use the Groovy metaclass to dynamically replace the default each() on a Java class.
I can see how to add new methods:
MyJavaClass.metaClass.myNewMethod = { closure -> /* custom logic */ }
new MyJavaClass().myNewMethod { item -> println item ...
We have a need to create SQLAlchemy classes to access multiple external data sources that will increase in number over time. We use the declarative base for our core ORM models and I know we can manually specify new ORM classes using the autoload=True to auto generate the mapping.
The problem is that we need to be able generate them dy...
How to call a method using getattr?
I want to create a metaclass, which can call non-existing methods of some other class that start with the word 'oposite_'. The method should have the same number of arguments, but to return the opposite result.
def oposite(func):
return lambda s, *args, **kw: not oposite(s, *args, **kw)
class ...
I need to be able to create forms from admin panel. Process would look like this:
I click on "Add form" then I enter email to which the form should be sent and of course several fields (probably thanks to inlines) consisting of field name, type and if it is required. User should be able to view and fill the form and submit it and the dat...
Normally, I might get the metaclass for a particular instance of a Ruby object with something like this:
class C
def metaclass
class << self; self; end
end
end
# This is this instance's metaclass.
C.new.metaclass => #<Class:#<C:0x01234567>>
# Successive invocations will have different metaclasses,
# since they're different ins...
Why is this:
class MyType(type):
def __init__(cls, name, bases, attrs):
print 'created', cls
class MyMixin:
__metaclass__ = MyType
class MyList(list, MyMixin): pass
okay, and works as expected:
created <class '__main__.MyMixin'>
created <class '__main__.MyList'>
But this:
class MyType(type):
def __init__(cls, n...
Hi,
I'd like to implement an object, that bounds values within a given range after arithmetic operations have been applied to it. The code below works fine, but I'm pointlessly rewriting the methods. Surely there's a more elegant way of doing this. Is a metaclass the way to go?
def check_range(_operator):
def decorator1(instance,_v...
I have an esoteric question involving Python metaclasses. I am creating a Python package for web-server-side code that will make it easy to access arbitrary Python classes via client-side proxies. My proxy-generating code needs a catalog of all of the Python classes that I want to include in my API. To create this catalog, I am using ...
I've read the official documentation and I understand what class references are but I fail to see when and why they are best solution compared to alternatives.
The example cited in the documentation is TCollection which can be instantiated with any descendant of TCollectionItem. The justification for using a class reference is that it a...
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))
...
Hello Stack Overflow contributers,
I'm a novice programmer learning Python right now, and I came upon this site which helps explain object-oriented paradigms. I know that metaclasses are classes of classes (like how meta-directories are directories of directories, etc. etc.), but I'm having trouble with something: What is the actual dif...
I have a class X which derives from a class with its own metaclass Meta. I want to also derive X from the declarative base in SQL Alchemy. But I can't do the simple
def class MyBase(metaclass = Meta):
#...
def class X(declarative_base(), MyBase):
#...
since I would get metaclass conflict error: 'the metaclass of a derived cl...
(All in ActivePython 3.1.2)
I tried to change the class (rather than instance) attributes. The __dict__ of the metaclass seemed like the perfect solution. But when I tried to modify, I got:
TypeError: 'dict_proxy' object does
not support item assignment
Why, and what can I do about it?
EDIT
I'm adding attributes inside the cla...
The following code doesn't compile; it says
NameError: name 'fields' is not
defined
in the last line. Is it because __new__ isn't called until after the fields assignment is reached? What should I do?
class Meta(type):
def __new__(mcs, name, bases, attr):
attr['fields'] = {}
return type.__new__(mcs, name, bas...
Hi all !
I am currently implementing a django app, for this I try to use a syntax that is consistent with Django's...
So here is what I am trying :
class Blablabla(Model):
#this contains Blablabla's options
class Meta:
sort_key = lambda e: e
sort_key is a key function (for sorting purposes), but of course, it is und...