Re: How do you implement this Python idiom in C++

2006-07-31 Thread alainpoint

Pierre Barbier de Reuille wrote:
 [EMAIL PROTECTED] wrote:
  Pierre Barbier de Reuille wrote:
 [...]
 
  I thank you for your response. The equivalent of your solution is
  posted hereunder:
  class cA(object):
  count=0
  def __init__(self):
  self.__class__.count +=1
  @classmethod
  def getcount(cls):
  return cls.count
  def __del__(self):
  self.__class__.count -=1
  class cB(cA):
  count=0
  def __init__(self):
  super(cB,self).__init__()
  for klass in self.__class__.__bases__:
  klass.count +=1
 
  a=cA() ; b=cA(); c= cA()
  d=cB() ; e=cB(); f= cB()
  a.a=1;b.a=1;c.a=1;d.a=1;e.a=1;f.a=1
  g=cA()
  g.a=1
  print  '#cA=',cA.getcount()  # 7
  print '#cB=',cB.getcount() #  3
  del g
  print  '#cA=',cA.getcount()  # 6
  print '#cB=',cB.getcount() #  3
 
  There is nothing impossible in Python ;-)
 
  Alain
 

 Well, nothing is impossible, but it is now much much more complex ! As a
 proof of that, your version does not work completely :P (try deleting d
 for example).

 I add a working version, but you will also notice that I have to
 *explicitly* walk over all the classes of the hierarchy, testing for the
 one who have a count attribute, hoping that this attribute is indeed
 for counting the number of objects and not anything else ... so the
 solution is quite fragile and very slow.

 class cA(object):
 count=0
 def __init__(self):
 self.__class__.count +=1
 for klass in self.__class__.__bases__:
 if hasattr( klass, count ):
 klass.count += 1

 @classmethod
 def getcount(cls):
 return cls.count
 def __del__(self):
 self.__class__.count -=1
 for klass in self.__class__.__bases__:
 if hasattr( klass, count ):
 klass.count -= 1
 class cB(cA):
 count=0

 a=cA() ; b=cA(); c= cA()
 d=cB() ; e=cB(); f= cB()
 a.a=1;b.a=1;c.a=1;d.a=1;e.a=1;f.a=1
 g=cA()
 g.a=1
 print  '#cA=',cA.getcount()  # 7
 print '#cB=',cB.getcount() #  3
 del g
 del d
 print  '#cA=',cA.getcount()  # 5
 print '#cB=',cB.getcount() #  2

 Pierre

Good point Pierre. But you'll have to admit that the class usage in
Python is much simpler (just derive from the class)
class cB(cA):
  count=0
contrarily to the C++ usage where you must remind the compiler of the
Counted class in every derived class.

In  Python, you have to bite only once thru the sour apple  


Alain

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do you implement this Python idiom in C++

2006-07-30 Thread alainpoint

Pierre Barbier de Reuille wrote:
 [EMAIL PROTECTED] wrote:
  Rob Williscroft wrote:
 
  If this is more than idle curiosity I strongly suggest you post
  a version of the python code you need to translate to C++.
 
  For the moment this is just healthy curiosity but i will still post the
  code i would like to see translated:
 
  class Parent:
  count=0
  def __init__(self):
  self.__class__.count +=1
  @classmethod
  def getcount(cls):
  return cls.count
 
  class Child(Parent):
  count=0 # replace this line by a 'pass'  statement if you don't want
  to reinitialise the count
 
  a=Parent()
  b=Parent()
  print Parent.getcount()  # you get 2
  c=Child()
  d=Child()
  e=Child()
  print Child.getcount() # you get 3 (you could get 5 if you don't
  reinitialise the count)
 
  This is as simple as it can get. I just derive from Parent and i get my
  proper count (added to my parent's if i wish so).
  I wish i could achieve such a code purity in C++.

 Well, I hope you understand that this code purity is possible only
 because of the *dynamic* lookup of the variable name ... Thus, the same
 function, once compiled, will be able to determine, at runtime, where
 the current variable lies ... At the same time, tries, in Python, to
 achieve the count of *all* the instances of a class, meaning that you want :

 a = Parent()
 b = Child()
 c = Parent()
 d = Child()
 print Child.getcount() # 2
 print Parent.getcount() # 4

 That time, the automatic name lookup will come in the way as you cannot
 have two count variables accessible from the same class.
 For C++ the problem is inverse, you have a way to obtain the second
 thing (using templates or macro), but the first is harder.

 Pierre

 PS: here is my solution in C++


 #include iostream
 using namespace std;

 template class T
 struct Counted
 {
   Counted() { ++count; }
   Counted( Counted const ) { ++count; }
   virtual ~Counted() { --count; }
   static size_t getCount() { return count; }
 protected:
   static size_t count;
 };

 template class T
 size_t CountedT::count = 0;

 struct cA : public CountedcA
 {
   int a;
 };

 struct cB : public CountedcB, public cA
 {
   // Needed to be sure of which getCount is called in cB
   using CountedcB::getCount;
 };

 int main()
 {
   cA a,b,c;
   cB d,e,f;
   a.a = 1;
   b.a = 1;
   c.a = 1;
   d.a = 1;
   e.a = 1;
   f.a = 1;
 {
 cA g;
 g.a = 1;
 cout  #cA =   cA::getCount()  endl; // 7
 cout  #cB =   cB::getCount()  endl; // 3
 }
   cout  #cA =   cA::getCount()  endl; // 6
   cout  #cB =   cB::getCount()  endl; // 3
   return 0;
 }

I thank you for your response. The equivalent of your solution is
posted hereunder:
class cA(object):
count=0
def __init__(self):
self.__class__.count +=1
@classmethod
def getcount(cls):
return cls.count
def __del__(self):
self.__class__.count -=1
class cB(cA):
count=0
def __init__(self):
super(cB,self).__init__()
for klass in self.__class__.__bases__:
klass.count +=1

a=cA() ; b=cA(); c= cA()
d=cB() ; e=cB(); f= cB()
a.a=1;b.a=1;c.a=1;d.a=1;e.a=1;f.a=1
g=cA()
g.a=1
print  '#cA=',cA.getcount()  # 7
print '#cB=',cB.getcount() #  3
del g
print  '#cA=',cA.getcount()  # 6
print '#cB=',cB.getcount() #  3

There is nothing impossible in Python ;-)

Alain

-- 
http://mail.python.org/mailman/listinfo/python-list


How do you implement this Python idiom in C++ ?

2006-07-27 Thread alainpoint
Hello,

I have the need to write the equivalent of Python class methods in C++.
Chuck Allison proposes the following
(http://www.artima.com/cppsource/simple.html):
#include iostream
using namespace std;

// A base class that provides counting
templateclass T class Counted {
  static int count;
public:
  Counted() { ++count; }
  Counted(const CountedT) { ++count; }
  ~Counted() { --count; }
  static int getCount() { return count; }
};

templateclass T int CountedT::count = 0;

// Curious class definitions
class CountedClass : public CountedCountedClass {};
class CountedClass2 : public CountedCountedClass2 {};

It apparently works but in fact it doesn't:
If you derive from such a class, you get the count of the parent class,
not of the derived class.
class CountedClass3 : public CountedClass {};

int main() {
  CountedClass a;
  cout  CountedClass::getCount()  endl;// 1
  CountedClass b;
  cout  CountedClass::getCount()  endl;// 2
  CountedClass3 c;
  cout  CountedClass3::getCount()  endl;   // 3 and should be 1
  cout  CountedClass::getCount()  endl;// 3 and should be 2
}

I am no C++ expert but i guess there might be some in the Python and
C++ newsgroups.

Alain

-- 
http://mail.python.org/mailman/listinfo/python-list


How do you implement this Python idiom in C++

2006-07-27 Thread alainpoint
Hello,

I have the need to write the equivalent of Python class methods in C++.

Chuck Allison proposes the following
(http://www.artima.com/cppsource/simple.html):
#include iostream
using namespace std;

// A base class that provides counting
templateclass T class Counted {
  static int count;
public:
  Counted() { ++count; }
  Counted(const CountedT) { ++count; }
  ~Counted() { --count; }
  static int getCount() { return count; }

};

templateclass T int CountedT::count = 0;

// Curious class definitions
class CountedClass : public CountedCountedClass {};
class CountedClass2 : public CountedCountedClass2 {};

It apparently works but in fact it doesn't:
If you derive from such a class, you get the count of the parent class,

not of the derived class.
class CountedClass3 : public CountedClass {};

int main() {
  CountedClass a;
  cout  CountedClass::getCount()  endl;// 1
  CountedClass b;
  cout  CountedClass::getCount()  endl;// 2
  CountedClass3 c;
  cout  CountedClass3::getCount()  endl;   // 3 and should be 1
  cout  CountedClass::getCount()  endl;// 3 and should be 2

}

I am no C++ expert but i guess there might be some in the Python and
C++ newsgroups. 

Alain

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do you implement this Python idiom in C++

2006-07-27 Thread alainpoint

Jon Clements wrote:
 [EMAIL PROTECTED] wrote:
  // Curious class definitions
  class CountedClass : public CountedCountedClass {};
  class CountedClass2 : public CountedCountedClass2 {};
 
  It apparently works but in fact it doesn't:
  If you derive from such a class, you get the count of the parent class,
 
  not of the derived class.
  class CountedClass3 : public CountedClass {};
 

 Hint: where's the template parameter gone as per the previous two
 statements...

 Jon.

You miss the point; i want to derive a class and inherit all properties
without worrying about those implementation details. The Python code is
much cleaner in that respect. My post is about whether it is possible
to get such a clean interface in C++

Alain

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do you implement this Python idiom in C++

2006-07-27 Thread alainpoint
Rob Williscroft wrote:

 If this is more than idle curiosity I strongly suggest you post
 a version of the python code you need to translate to C++.

For the moment this is just healthy curiosity but i will still post the
code i would like to see translated:

class Parent:
count=0
def __init__(self):
self.__class__.count +=1
@classmethod
def getcount(cls):
return cls.count

class Child(Parent):
count=0 # replace this line by a 'pass'  statement if you don't want
to reinitialise the count

a=Parent()
b=Parent()
print Parent.getcount()  # you get 2
c=Child()
d=Child()
e=Child()
print Child.getcount() # you get 3 (you could get 5 if you don't
reinitialise the count)

This is as simple as it can get. I just derive from Parent and i get my
proper count (added to my parent's if i wish so).
I wish i could achieve such a code purity in C++.

Alain

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do you implement this Python idiom in C++

2006-07-27 Thread alainpoint

Noah Roberts wrote:
 What happens if you print Parent.getcount() now?

You still get 2 since there is no new instance of Parent that was
created.

Alain

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: comparing of python GUIĀ“s

2006-06-20 Thread alainpoint

Bayazee wrote:
 ThanX ...
 any idea for choosing one of them ?
 best in linux  windows
 i must write a cross platform project .
 it is a chat server and client with a user end site .
 i started by writing a web site and creating a database in MySQL (FC4)
 .
 now i want to write a client with gui . similir to yahoo messenger or
 ...
 whats your suggest ?

You probably didn't notice but Tim's post was meant to be humorous ;-)
Go back to my advice.
Once you're proficient with Google (it might take you some time), go
and search for previous discussions on the same subject.

Alain

-- 
http://mail.python.org/mailman/listinfo/python-list


Just out of curiosity: Which languages are they using at Google and what for?

2006-06-19 Thread alainpoint
I know Google are using Python for testing purposes.
But for the rest ?
is it PHP or Java or .NET?
Which technology is rendering the google main page?

And of course th obvious question, why not Python?

Alain

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: challenging (?) metaclass problem

2006-04-11 Thread alainpoint

 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

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: challenging (?) metaclass problem

2006-04-11 Thread alainpoint

 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

-- 
http://mail.python.org/mailman/listinfo/python-list


challenging (?) metaclass problem

2006-04-10 Thread alainpoint
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

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: challenging (?) metaclass problem

2006-04-10 Thread alainpoint
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

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: DO NOT USE JAVA BECAUSE IT IS NOT OPEN SOURCE

2006-04-03 Thread alainpoint
Bravo, yoo r write, a propriatary languish is an oxy-moron. I have a
rekwest zou: witch languish do yoo rekomend, bikoos yoo seem so a grate
programor, at list zis is wat eye beleve, judging by yoo spelling.
Alain

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is this possible in Python? SOLUTION FOUND

2006-03-14 Thread alainpoint

jalanb wrote:
 You might like the version here:
 http://www.jorendorff.com/toys/out.html

 Especially the need to know presentation, which is cute

 --
 Alan
 http://aivipi.blogspot.com

Thank you for the tip.
Meanwhile, I found a shorter solution to my problem:
def magic(arg):
import inspect
return inspect.stack()[1][4][0].split(magic)[-1][1:-1]

assert magic(3+4)==3+4

Alain

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is this possible in Python? SOLUTION FOUND

2006-03-14 Thread alainpoint

Kay Schluehr wrote:
 [EMAIL PROTECTED] wrote:
  jalanb wrote:
   You might like the version here:
   http://www.jorendorff.com/toys/out.html
  
   Especially the need to know presentation, which is cute
  
   --
   Alan
   http://aivipi.blogspot.com
 
  Thank you for the tip.
  Meanwhile, I found a shorter solution to my problem:
  def magic(arg):
  import inspect
  return inspect.stack()[1][4][0].split(magic)[-1][1:-1]
 
  assert magic(3+4)==3+4
 
  Alain

 Does it? Using your function I keep an assertion error. Storing the
 return value of magic()in a variable s I receive the following result:

 def magic(arg):
 import inspect
 return inspect.stack()[1][4][0].split(magic)[-1][1:-1]

 s = magic(3+4) # magic line

  s
 'lin'


 BTW grepping the stack will likely cause context sensitive results.

 Kay


This is no production-ready code, just a proof of concept.
Adding 3 or 4 lines would make it more robust.
Just hope someone else will benefit from this discussion.

Alain

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is this possible in Python?

2006-03-14 Thread alainpoint

Steven D'Aprano wrote:


 Doesn't work for me either:

  def magic(arg):
 ... import inspect
 ... return inspect.stack()[1][4][0].split(magic)[-1][1:-1]
 ...
  magic(3+4)
 Traceback (most recent call last):
   File stdin, line 1, in ?
   File stdin, line 3, in magic
 TypeError: unsubscriptable object


 Kay gets an AssertionError, I get a TypeError. I think describing it as
 proof of concept is rather optimistic.

 Here is the inspect.stack() I get:

 [(frame object at 0x825d974, 'stdin', 2, 'magic', None, None),
 (frame object at 0x8256534, 'stdin', 1, '?', None, None)]


 --
 Steven.

You just proved what i was saying: this is no robust code. It
apparently does not work from the command line. It has problems with
comments on the same line. It might have problems with multi-line
arguments, etc 
Please feel free to improve the above function and make it robust.
(meanwhile, i removed the SOLUTION FOUND from the subject title, until
you come up with such a robust version ;-))
Alain

-- 
http://mail.python.org/mailman/listinfo/python-list


Is this possible in Python?

2006-03-13 Thread alainpoint
Hi

I wonder if Python is capable of the following: define a function which
returns its argument.
I mean:
def magic_function(arg):
.. some magic code ...

that behaves the following way:

assert magic_function(3+4)==3+4
assert magic_function([i for i in range(10)])==i for i in range(10)]

It is not trivial at all and might require some bytecode hacking that i
am unable to do myself BUT you are the experts ;-)

Alain

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is this possible in Python?

2006-03-13 Thread alainpoint

Kay Schluehr wrote:
 Storing arguments away before they are evaluated doesn't work in
 Python. You have to hack the compiler in order to access the parsetree.
 You might take a look at the compiler package of the standard library
 that enables access to ASTs. Thus you could define lazy evaluation and
 just-in-time compilation of some particular ASTs. I do not recommend
 doing this for real purposes, but it is a good excercise and sooner or
 later you become an expert yourself :)

 Kay

I made some investigation and reached a (partial) solution to my
problem. It is inspired from a cookbook recipe but it only works for
generator expressions.:
import tokenize
import token
def magic_function(s):
cursor = None   # to be set to the cursor of the connection
return_type = object# can be set to dict or list
_iterating = False # used in next()
readline = open(s.gi_frame.f_code.co_filename).readline
first_line = s.gi_frame.f_code.co_firstlineno
flag = False
source = ''# the source code
for t in
tokenize.generate_tokens(open(s.gi_frame.f_code.co_filename).readline):
# check all tokens until the last parenthesis is closed
t_type,t_string,(r_start,c_start),(r_end,c_end),line = t
t_name = token.tok_name[t_type]
if r_start == first_line:
if t_name == 'NAME' and t_string==magic_function:
flag = True
res = t_string
start = 0 # number of parenthesis
continue
if flag:
source += ' '+t_string
if t_name == 'OP':
if t_string=='(':
start += 1
elif t_string == ')':
start -= 1
if start == 0:
break
return source[2:-2]

assert magic_function(i+2 for i in [1,2])==i+2 for i in [1,2]
or
print magic_function(i+2 for i in [1,2])

A general solution is possible and i am sure there are people around
that will provide such a solution

Alain

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is this possible in Python?

2006-03-13 Thread alainpoint
Hello again,
I am disappointed. You are the experts, you've got to try harder ;-)
What i want is a generalisation of this tiny function:
import tokenize
import token
def magic_function(s):
readline = open(s.gi_frame.f_code.co_filename).readline
for t in
tokenize.generate_tokens(open(s.gi_frame.f_code.co_filename).readline):
t_type,t_string,(r_start,c_start),(r_end,c_end),line = t
if r_start == s.gi_frame.f_code.co_firstlineno:
if t_string==magic_function:
args= line.split(t_string)
arg=args[1]
return arg
# returns its own argument !
print magic_function(i+2 for i in [1,2])

There ought to be a way to make it work for more than generator
expressions !!!

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is this possible in Python?

2006-03-13 Thread alainpoint
Hi Kent,
My intention is to be able to retrieve any line of code in a running
program, in the following way:
def magic_funct(s):
for line in file(s.gi_frame.f_code.co_filename):
print line
magic_funct(i for i in [1,2,3])

I just find it stupid to be obliged to use a generator expression, just
because it has got the gi_frame attribute. Such a kind of introspection
can be very useful.
I don't want a better way, i just want a solution to the problem as
described!

Alain

-- 
http://mail.python.org/mailman/listinfo/python-list


class variables for subclasses tuple

2006-03-08 Thread alainpoint
Hello,

I have got a problem that i can't readily solve.
I want the following:
I want to create a supertuple that behaves both as a tuple and as a
class.
It should do the following:
Point=superTuple(x,y,z) # this is a class factory
p=Point(4,7,9)
assert p.x==p[0]
assert p.y==p[1]
assert p.z==p[2]
I already found a recipe to do that (recipe 6.7 in the Python
cookbook). I reproduce the code hereunder:
def superTuple(*attribute_names):
 create and return a subclass of `tuple', with named attributes 
# make the subclass with appropriate _ _new_ _ and _ _repr_ _
specials
typename='Supertuple'
nargs = len(attribute_names)
class supertup(tuple):
_ _slots_ _ = ( ) # save memory, we don't need
per-instance dict
def _ _new_ _(cls, *args):
if len(args) != nargs:
raise TypeError, '%s takes exactly %d arguments (%d
given)' % (
  typename, nargs, len(args))
return tuple._ _new_ _(cls, args)
def _ _repr_ _(self):
return '%s(%s)' % (typename, ', '.join(map(repr, self)))
# add a few key touches to our new subclass of `tuple'
for index, attr_name in enumerate(attribute_names):
setattr(supertup, attr_name, property(itemgetter(index)))
supertup._ _name_ _ = typename
return supertup

Now my problem is: i would like to extend this supertuple with class
variables so that i can obtain the following:
assert Point.x==0
assert Point.y==1
assert Point.z==2
while still having:
assert p.x==p[0]
assert p.y==p[1]
assert p.z==p[2]
This is not the case unfortunately:
Point.x=0 leads to having p.x==0
It seems not possible to have class variables and instance variable
having the same name and yet different values.
Alain

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: class variables for subclasses tuple

2006-03-08 Thread alainpoint

Peter Otten wrote:
 [EMAIL PROTECTED] wrote:

  Point.x=0 leads to having p.x==0
  It seems not possible to have class variables and instance variable
  having the same name and yet different values.

 A quick check:

  class T(tuple):
 ... class __metaclass__(type):
 ... x = property(lambda cls: 0)
 ... x = property(lambda self: self[0])
 ...
  t = T(abc)
  t.x
 'a'
  T.x
 0

 So possible it is. Come back if you're stuck generalizing the above.

 Peter

Thanks for your magic answer.
But i am not so good at magic ;-)
If i want to generalize to a arbitrary number of variables, i got
syntax errors.
Within a class, you can only method/class definitions and assignments.
It is therefore difficult to do something like:
for idx, attr_name in enumerate(attribute_names):
setattr(__metaclass__,attr_name, property(lambda cls:idx)
for idx, attr_name in enumerate(attribute_names):
setattr(T,attr_name, property(lambda self:self[idx])

Alain

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: class variables for subclasses tuple

2006-03-08 Thread alainpoint
As an supplement to my previous post, please find hereunder a snippet
for my unsuccessful attempt (commented out snippet does not work):
def superTuple(*attribute_names):
nargs = len(attribute_names)
class T(tuple):
def __new__(cls, *args):
return tuple.__new__(cls, args)
class __metaclass__(type):
x=property(lambda self:0)
y=property(lambda self:1)
z=property(lambda self:2)
x=property(lambda self:self[0])
y=property(lambda self:self[1])
z=property(lambda self:self[2])
#for idx, attr_name in enumerate(attribute_names):
#   print 'attr name',attr_name, idx
#   setattr(T.__metaclass__,attr_name, property(lambda cls:idx))
#for idx, attr_name in enumerate(attribute_names):
#   print 'attr name',attr_name
#   setattr(T,attr_name, property(lambda self:self[idx]))
return T
if __name__ == '__main__':
Point=superTuple('x','y','z')
p=Point(4,7,9)
assert p.x==p[0]
assert p.y==p[1]
assert p.z==p[2]
assert Point.x==0
assert Point.y==1
assert Point.z==2

Alain

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: class variables for subclasses tuple

2006-03-08 Thread alainpoint
Thank you Peter, this does the job.
In passing, I have another question: where can I read up more on
metaclasses?
Alain

-- 
http://mail.python.org/mailman/listinfo/python-list


Python interpreter bug

2005-10-07 Thread alainpoint
Hello,

I came accross what i think is a serious bug in the python interpreter.

Membership testing seems not to work for list of objects when these
objects have a user-defined __cmp__ method.
It is present in Python 2.3 and 2.4. I don't know about other versions.
The following code illustrates the bug:
from random import choice
class OBJ:
def __init__(self,identifier):
self.id=identifier
self.allocated=0
def __cmp__(self,other):
return cmp(other.allocated,self.allocated)
mylist=[OBJ(i) for i in range(20)]
excluded=[obj for obj in mylist if obj.idchoice(range(20))]
for obj in mylist:
if obj in excluded:
assert obj.id in [objt.id for objt in excluded]
continue

Running the above snippet will trigger the assert. The culprit seems to
be the __cmp__ method which sorts on a key with constant value.
Best regards
Alain

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python interpreter bug

2005-10-07 Thread alainpoint
There is definitely a bug.
Maybe the follownig snippet is more clear:
class OBJ:
def __init__(self,identifier):
self.id=identifier
self.allocated=0
#def __cmp__(self,other):
#   return cmp(other.allocated,self.allocated)
mylist=[OBJ(i) for i in range(10)]
excluded=[obj for obj in mylist if obj.id in [2,4,6,8]]
exclusion_list_by_id=[2,4,6,8]
print 'exclusion list by id=',exclusion_list_by_id
for obj in mylist:
print 'current obj=',obj.id,
if obj in excluded:
print ' --- THIS OBJECT IS EXCLUDED'
assert obj.id in exclusion_list_by_id
continue
print

If you uncomment the two lines, the assert will be erroneously
triggered.
Alain

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python interpreter bug

2005-10-07 Thread alainpoint
Sorry Fredrik but I don't understand. Just comment out the assert and
you have different results depending on whether an unrelated sort
function is defined.
This seems weird to me !

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python interpreter bug

2005-10-07 Thread alainpoint
I understand this, Steve.
I thought the _cmp_ method was a helper for sorting purposes. Why is it
that a membership test needs to call the __cmp__ method?
If this isn't a bug, it is at least unexpected in my eyes.
Maybe a candidate for inclusion in the FAQ?
Thank you for answering
Alain

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python interpreter bug

2005-10-07 Thread alainpoint
In fact, i want to sort the list based on the 'allocated attribute' and
at the same time, test membership based on the id attribute.
__cmp__ logically implies an ordering test, not an identity test. These
two notions seems to be confounded in python which is unfortunate. Two
objects could have the same rank while still being different.
Alain

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python interpreter bug

2005-10-07 Thread alainpoint
No doubt you're right but common sense dictates that membership testing
would test identity not equality.
This is one of the rare occasions where Python defeats my common sense
;-(

Alain

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python interpreter bug

2005-10-07 Thread alainpoint
 Steve Holden wrote:
Consider:

  a = {1:'one'}
  b = {2:'two'}
  c = {1:'one'}
  a is c
False
  a in [b, c]
True
 


What would you have Python do differently in these circumstances?

You mean: What i would do i if i was the benevolent dictator ?
I would make a distinction between mutables and immutables. Immutables
would test for equality and mutables would test for identity.
Membership testing for objects is a very common use case which is
totally unrelated to their being sorted according to a key.
I am no expert on languages so i could be wrong. Don't hesitate to
correct me.
Alain

-- 
http://mail.python.org/mailman/listinfo/python-list


Elementtree and CDATA handling

2005-06-01 Thread alainpoint
I am experimenting with ElementTree and i came accross some
(apparently) weird behaviour.
I would expect a piece of XML to be read, parsed and written back
without corruption (except for the comments and PI which have purposely
been left out). It isn't however the case when it comes to CDATA
handling.
I have the following code:
text=htmlhead
titleDocument/title
/head
body
script type=text/javascript
//![CDATA[
function matchwo(a,b)
{
if (a  b  a  0) then
   {
   return 1
   }
}
//]]
/script
/body
/html


from elementtree import ElementTree
tree = ElementTree.fromstring(text)
ElementTree.dump(tree)

Running the above piece of code yields the following:

htmlhead
titleDocument/title
/head
body
script type=text/javascript
//
function matchwo(a,b)
{
if (a lt; b amp;amp; a gt; 0) then
   {
   return 1
   }
}
//
/script
/body
/html

There are two problems: the //![CDATA[  has disappeared and the , 
and  have been replaced by their equivalent entities (CDATA should
have prevented that).
I am no XML/HMTL expert, so i might be doing something wrong...
Thank you for helping

Alain

-- 
http://mail.python.org/mailman/listinfo/python-list


Bug in Elementtree/Expat

2005-05-17 Thread alainpoint
Hello,

I use Elementtree to parse an elementary SVG file (in fact, it is one
of the examples in the SVG essentials book). More precisely, it is
the fig0201.svg file in the second chapter.
The contents of the file are as follows (i hope it will be rendered
correctly):
!DOCTYPE svg PUBLIC -//W3C//DTD SVG 1.0//EN
http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd;
svg width=200 height=200
titleDefault User Coordinates/title
descShows a rectangle on a grid in default user coordinates/desc
image xlink:href=default_ruler.svg x=0 y=0 width=200
height=200/
g transform=translate(40,40)
rect x=10 y=10 width=50 height=30style=stroke: black; fill:
none;/
/g
/svg

The parsing fails in the following way:
Traceback (most recent call last):
  File C:\privatedata\myapp.py, line 60, in ?
root = ElementTree(file=infile).getroot()
  File c:\python23\lib\site-packages\elementtree\ElementTree.py, line
554, in __init__
self.parse(file)
  File c:\python23\lib\site-packages\elementtree\ElementTree.py, line
594, in parse
parser.feed(data)
  File c:\python23\lib\site-packages\elementtree\ElementTree.py, line
1171, in feed
self._parser.Parse(data, 0)
xml.parsers.expat.ExpatError: unbound prefix: line 6, column 1


The problem seems to lie with the xlink:href tag. If i remove the xlink
namespace, it then does not produce a traceback.

Thank you for helping
Alain

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bug in Elementtree/Expat

2005-05-17 Thread alainpoint

Fredrik Lundh wrote:

 adding

 xmlns:xlink=http://www.w3.org/1999/xlink;

 to the svg element should make the problem go away.


Thanks for the tip. It indeed solves the problem.
Most examples in the book do not include such a declaration and yet are
properly rendered by Internet Explorer.
Is it mandatory and why is it that Expat crashes on it?

Alain

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which is easier? Translating from C++ or from Java...

2005-03-28 Thread alainpoint

Patrick Useldinger wrote:
 cjl wrote:

 Depends on what language you know best. But Java is certainly easier
to  read than C++.


There is a difference between theory and practice. In theory, Java is
easier to read than C++.
In practice however, the average Java programmer is MUCH less talented
than the average C++ programmer (let alone the average Python
programmer). The upshot of all this is that in practice (and my own
personal experience: we use both C++ and Java), Java code is bloated
with design patterns, obfuscated with many layers of indirection,
etc...
As a summary, Java code can most of the time be thrown away and
re-written from scratch (the fastest way). C++ code on the contrary can
easily be ported/wrapped.
Of course this is a matter of personal opinion. I love neither Java nor
C++. C is for me the purest language and there is no match when
combined with Python !

My 2 cents

Alain

-- 
http://mail.python.org/mailman/listinfo/python-list