473,320 Members | 2,133 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,320 software developers and data experts.

challenging (?) metaclass problem

Hi,

I have what in my eyes seems a challenging problem.
Thanks to Peter Otten, i got the following code to work. It is a sort
of named tuple.
from operator import itemgetter
def constgetter(value):
def get(self): return value
return get
def createTuple(*names):
class TupleType(type):
pass
class T(tuple):
__metaclass__ = TupleType
def __new__(cls, *args):
if len(names) != len(args):
raise TypeError
return tuple.__new__(cls, args)
for index, name in enumerate(names):
setattr(T, name, property(itemgetter(index)))
setattr(TupleType, name, property(constgetter(index)))
return T
if __name__ == '__main__':
Point=makeTuple('x','y')
p=Point(4,7)
assert p.x==p[0]
assert p.y==p[1]
assert Point.x==0
assert Point.y==1

Now my problem is the following. I want to write a function called
createDerivedTuple in order to create a class derived from the one
created with the function createTuple, taking the parent class as first
argument:
def createDerivedTuple(parentclass,*names):
....... code yet to be figured out ....

The usage should be as follows:

DerivedPoint=makeDerivedTuple(Point,'z')
p=DerivedPoint(4,7,9)
assert p.x==p[0]
assert p.y==p[1]
assert p.z==p[2]
assert DerivedPoint.x==0
assert DerivedPoint.y==1
assert DerivedPoint.z==2

I am still a newbie on metaclasses but i am convinced there are elegant
solutions to this challenging problem.

Best regards

Alain

Apr 10 '06 #1
5 1216
Now, a tab-free version of my previous post. (Sorry for the
inconvenience)
Hi,
I have what in my eyes seems a challenging problem.
Thanks to Peter Otten, i got the following code to work. It is a sort
of named tuple.
from operator import itemgetter
def constgetter(value):
def get(self): return value
return get
def createTuple(*names):
class TupleType(type):
pass
class T(tuple):
__metaclass__ = TupleType
def __new__(cls, *args):
if len(names) != len(args):
raise TypeError
return tuple.__new__(cls, args)
for index, name in enumerate(names):
setattr(T, name, property(itemgetter(index)))
setattr(TupleType, name, property(constgetter(index)))
return T
if __name__ == '__main__':
Point=makeTuple('x','y')
p=Point(4,7)
assert p.x==p[0]
assert p.y==p[1]
assert Point.x==0
assert Point.y==1
Now my problem is the following. I want to write a function called
createDerivedTuple in order to create a class derived from the one
created with the function createTuple, taking the parent class as first

argument:
def createDerivedTuple(parentclass,*names):
....... code yet to be figured out ....
The usage should be as follows:
DerivedPoint=makeDerivedTuple(Point,'z')
p=DerivedPoint(4,7,9)
assert p.x==p[0]
assert p.y==p[1]
assert p.z==p[2]
assert DerivedPoint.x==0
assert DerivedPoint.y==1
assert DerivedPoint.z==2
I am still a newbie on metaclasses but i am convinced there are elegant

solutions to this challenging problem.
Best regards
Alain

Apr 10 '06 #2
al********@yahoo.fr wrote:
I have what in my eyes seems a challenging problem.
Thanks to Peter Otten, i got the following code to work. It is a sort
of named tuple.
Don't trust code posted in a newsgroup -- it may sometimes be
quality-challenged :-)
Now my problem is the following. I want to write a function called
createDerivedTuple in order to create a class derived from the one
created with the function createTuple, taking the parent class as first
argument:
def createDerivedTuple(parentclass,*names):
....... code yet to be figured out ....

The usage should be as follows:

DerivedPoint=makeDerivedTuple(Point,'z')
p=DerivedPoint(4,7,9)
assert p.x==p[0]
assert p.y==p[1]
assert p.z==p[2]
assert DerivedPoint.x==0
assert DerivedPoint.y==1
assert DerivedPoint.z==2

I am still a newbie on metaclasses but i am convinced there are elegant
solutions to this challenging problem.


Hey, if you don't try to solve it yourself we'll end up with me learning
more than you...

I didn't find a way to extend the approach with a per-class metaclass to
support inheritance. I think you would have to subclass both class and
metaclass. So I had to start all over again:

class IndexProperty(object):
def __init__(self, index):
self.index = index
def __get__(self, inst, cls):
index = self.index
if inst is None:
return index
return inst[index]

class TupleType(type):
def __new__(mcl, name, bases, classdict):
names = classdict.get("_names")
if names is not None:
for base in bases:
base_names = getattr(base, "_names", None)
if base_names is not None:
offset = len(base_names)
break
else:
offset = 0
for i, n in enumerate(names):
classdict[n] = IndexProperty(offset + i)
if offset:
names[:0] = base_names
return type.__new__(mcl, name, bases, classdict)

class Tuple(tuple):
__metaclass__ = TupleType
def __new__(cls, values):
self = tuple.__new__(cls, values)
if len(self) != len(cls._names):
raise TypeError
return self

import unittest

class P2(Tuple):
_names = ["x", "y"]

class P3(P2):
_names = ["z"]

def yield_them(seq):
"""Helper to ensure the implementation cannot rely on len()."""
for item in seq:
yield item

class Test(unittest.TestCase):
def test_P2(self):
self.assertEquals(P2.x, 0)
self.assertEquals(P2.y, 1)
self.assertRaises(AttributeError, lambda: P2.z)

def test_P3(self):
self.assertEquals(P3.x, 0)
self.assertEquals(P3.y, 1)
self.assertEquals(P3.z, 2)

def test_P2_inst(self):
self.assertRaises(TypeError, P2, yield_them("A"))
self.assertRaises(TypeError, P2, yield_them("ABC"))

p = P2(yield_them("AB"))
self.assertEquals(p.x, "A")
self.assertEquals(p.y, "B")
self.assertRaises(AttributeError, lambda: p.z)

def test_P3_inst(self):
self.assertRaises(TypeError, P3, yield_them("A"))
self.assertRaises(TypeError, P3, yield_them("ABCD"))

p = P3(yield_them("ABC"))
self.assertEquals(p.x, "A")
self.assertEquals(p.y, "B")
self.assertEquals(p.z, "C")

self.assertRaises(AttributeError, lambda: p.t)
if __name__ == "__main__":
unittest.main()

I did not perform any tests other than the unittest given above.

Peter
Apr 10 '06 #3

Hi Peter,

I don't know if you noticed but i changed my mind and removed the post
as i realised that people seemed to have much more interest in how
relevant c code still is than in solving an interesting problem.
I only speak French and Dutch and my knowledge of Belgium's third
official language (German) is only passive. Otherwise i would have
posted on the german newsgroup (the French newsgroup does not seem to
be so interesting and there are no belgian or dutch newsgroups either).
Anyway, thank you for accepting the challenge. I'll try out your code
and get back if i have any problem.

Viele dank.

Alain

Apr 11 '06 #4

Hi Peter,

I don't know if you noticed but i changed my mind and removed the post
as i realised that people seemed to have much more interest in how
relevant c code still is than in solving an interesting problem.
I only speak French and Dutch and my knowledge of Belgium's third
official language (German) is only passive. Otherwise i would have
posted on the german newsgroup (the French newsgroup does not seem to
be so interesting and there are no belgian or dutch newsgroups either).
Anyway, thank you for accepting the challenge. I'll try out your code
and get back if i have any problem.

Viele dank.

Alain

Apr 11 '06 #5
al********@yahoo.fr wrote:
I don't know if you noticed but i changed my mind and removed the post
No, I didn't. It seems to be kept in the cache of my newsreader.
as i realised that people seemed to have much more interest in how
relevant c code still is than in solving an interesting problem.
Oh the defeatism. The chance that you might get an answer is a perfect
reason to ask. That you might get no answer is no reason not to.
I only speak French and Dutch and my knowledge of Belgium's third
official language (German) is only passive. Otherwise i would have
posted on the german newsgroup (the French newsgroup does not seem to
be so interesting and there are no belgian or dutch newsgroups either).
Anyway, thank you for accepting the challenge. I'll try out your code
and get back if i have any problem.
I don't think you are more likely to get an answer on the national
newsgroups. Python addicts frequent groups in both English and vernacular.
Viele dank.


Gern geschehen.

Peter
Apr 11 '06 #6

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

Similar topics

3
by: Fernando Rodriguez | last post by:
Hi, I'm having trouble with a metaclass suposed to check the method signature of its classes. Here's the metaclass: class MetaChecker(type): def __new__(cls, name, bases, attribs): for...
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...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
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)...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
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...

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.