Hi,
I've been looking at writing parameterized metaclasses and here are the
two solutions I've come to:
(my goal was to build a way to automatically add a hash function that
would take into account a selected list of object attributes)
1. all-in-one metametaclass:
class Autohash2(type):
"""
Metametaclass that instantiates into a metaclass creating
a hash function based on the attributes passed on instantiation.
"""
def __new__(cls, hash_attributes):
def class_new(cls, name, bases, d):
print "New class", name
l = hash_attributes
_hash = hash
_tuple = tuple
c = _hash(_tuple([_hash(k) for k in l]))
def object_hash(obj):
g = obj.__getattribute__
return _hash(_tuple([_hash(g(k)) for k in l]))
d['__hash__'] = object_hash
return super(Autohash2, cls).__new__(cls, name, bases, d)
name = '__private'
bases = (type,)
d = {'__new__': class_new}
print "New metaclass", name
return type.__new__(cls, name, bases, d)
2. with the metametaclass property slightly abstracted away:
class Metametaclass(type):
def __new__(cls, name, bases, dict_):
d = { '__new__': dict_['class_new'] }
def meta_new(cls, *args, **kargs):
print "New metaclass"
name = '__private'
bases = (type,)
return super(Metametaclass, cls).__new__(cls, name, bases, d)
dict_['__new__'] = meta_new
print "New metametaclass", name
return type.__new__(cls, name, bases, dict_)
class Autohash(type):
__metaclass__ = Metametaclass
def __init__(cls, hash_attributes):
cls.hash_attributes = hash_attributes
def class_new(cls, name, bases, d):
print "New class", name
l = cls.hash_attributes
_hash = hash
_tuple = tuple
c = _hash(_tuple([_hash(k) for k in l]))
def object_hash(obj):
g = obj.__getattribute__
return _hash(_tuple([_hash(g(k)) for k in l]))
d['__hash__'] = object_hash
return super(Autohash, cls).__new__(cls, name, bases, d)
Both of those metametaclasses can be used (successfully!) in the
following way:
class Address(object):
__metaclass__ = Autohash3(('host', 'port'))
# <snip rest of class definition>
a = Address()
a.host = 'localhost'
a.port = 5555
b = copy.copy(a)
hash(a) == hash(b)
I was wondering if there is some simpler way of building parameterized
metaclasses ?
Regards
Antoine. 1 2242
> I was wondering if there is some simpler way of building
parameterized metaclasses ?
Why not just a function returning metaclasses?
def metaFactory(*args):
dic = <something possibly depending on args>
return type("somemetaclass", (type,), dic)
Alternatively, a metaclass classmethod returning a metaclass, so that
you can use something like
__metaclass__ = MyMetaclass.with(*args) # classmethod returning a
metaclass
Michele Simionato This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Robin Becker |
last post by:
A colleague wanted to initialize his class __new__ and tried code resembling this
#######################1
class Metaclass (type):
def __init__(cls, name, bases, *args, **kwargs):...
|
by: Irmen de Jong |
last post by:
Hi,
I've developed the Metaclass below, because I needed a way
to make a bunch of classes thread-safe.
I didn't want to change every method of the class by adding
lock.aqcuire()..lock.release()...
|
by: Jacek Generowicz |
last post by:
I would like to write a metaclass which would allow me to overload
names in the definition of its instances, like this
class Foo(object):
__metaclass__ = OverloadingClass
att = 1
att = 3
|
by: zipher |
last post by:
After searching through comp.lang.python and the web regarding
metaclasses, I could not find an example for customing classes using
metaclass parameters.
I want to be able to create a class at...
|
by: ironfroggy |
last post by:
Hoping this isn't seeming too confusing, but I need to create a
metaclass and a class using that metaclass, such that one of the bases
of the metaclass is the class created with that metaclass. I...
|
by: Pedro Werneck |
last post by:
Hi
I have a class A, with metaclass M_A, and class B, subclass of A, with
metaclass M_B, subclass of M_A.
A class C, subclass of B must have M_B or a subclass of it as metaclass,
but what if...
|
by: Christian Eder |
last post by:
Hi,
I think I have discovered a problem in context of
metaclasses and multiple inheritance in python 2.4,
which I could finally reduce to a simple example:
Look at following code:
class...
|
by: Pedro Werneck |
last post by:
Hi all
I noticed something strange here while explaining decorators to someone.
Not any real use code, but I think it's worth mentioning.
When I access a class attribute, on a class with a...
|
by: lbolognini |
last post by:
Hi all,
I dare risk my brain exploding by reaching for the understanding of
metaclasses.
At first i thought i almost got them, even if vaguely back in a corner
of my mind, my understanding...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: Vimpel783 |
last post by:
Hello!
Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
|
by: ArrayDB |
last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
|
by: PapaRatzi |
last post by:
Hello,
I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
|
by: CloudSolutions |
last post by:
Introduction:
For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
|
by: Shællîpôpï 09 |
last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
|
by: af34tf |
last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
|
by: Faith0G |
last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome former...
| |