473,322 Members | 1,523 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

parameterized metaclass (or metametaclass)


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.
Jul 18 '05 #1
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

Jul 18 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
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):...
5
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()...
33
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
2
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...
16
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...
14
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...
9
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...
4
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...
2
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...
0
isladogs
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...
0
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...
0
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...
1
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)...
1
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...
1
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....
0
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
0
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...
0
isladogs
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...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.