boa constructor & mysql

2005-01-28 Thread Michele
I've search a lot to found how visualize a mysql table in a gui (wxpython).
I think to use wxgrid to visualize this table...but I don't know how...
Anyone help me?
Thanks a lot for the patience.
Michele
--
http://mail.python.org/mailman/listinfo/python-list


Re: Designing a cancellable function

2006-12-15 Thread Michele
Hi Leo,

what about one (or more) thread(s) which run the eat() method of
FilesEater object with inheriths from a superclass what's needed to
update the progress attribute (for example a _inc_progress() private
method)? (So you can have a UrlEater class and so on, them all knowing
how to update their progress)
Then you give FilesEater (or maybe a better name) a reference to a
config dict at init time.

You can have multiple FilesEater with different configurations and you
can handle the problem of stopping execution with a stopEating()
public method which sets an internal flag (a Lock object) and you
check it inside the object runloop with something like:

def eat(self):
  for f in self.files:
do_some_stuff()
self._eat_for_real()
do_some_other_stuff()

def _eat_for_real(): # you should use the with statement inside here =)
  self._eatLock.acquire()
  do_the_processing
  _write_the_result() # !
  self._eatLock.release()

with this you can pause and restart the execution by calling
pause/restart methods that acquire and release the eatLock. It writes
the result before releasing it so you know it finishes the last chunk
when you suspend it.
If then you want to abord, just call the pause() on every *Eater
object and exit.
If you want to exit immediately just exit and design the code that
reads the output of the eat() processing in a way that it can
recognize broken chunks, delete them and go on (if they are written
on-disk obviously).

Hope this helps,
Michele


On 16 Dec 2006 01:20:47 GMT, Leo Breebaart <[EMAIL PROTECTED]> wrote:
> I have written a function foo() that iterates over and processes
> a large number of files. The function should be available to the
> user as library function, via a command-line interface, and
> through a GUI.
>
> So, I added a 'config' object as a parameter to foo() that can be
> used by the caller to explicitly pass in user-defined settings.
> Because the processing foo() does can take such a long time, the
> next thing I did was add an 'update_function' callback parameter
> that foo() will call regularly, so that the GUI can update a
> progress bar, and the command-line version can print dots, etc.
>
> I now would also like to add the possibility to allow the user to
> *cancel* the execution of foo() during the processing, and I am
> wondering what the best / most Pythonic way to design this is.
>
> One obvious approach seems to me to turn the 'config' object into
> something more dynamic, and have foo() regularly inspect it to
> see if somebody in the main thread has set e.g. config.abort to
> True.
>
> Another approach would be to turn foo() into a proper (threaded)
> class with distinct run() and abort() methods. But the caller
> would still need to register the update callback somehow, and I
> am wondering if this way the whole API for foo() won't become to
> complex and overdesigned.
>
> I was wondering if anybody has any insights or best practice
> recommendations for me here. Do I keep the function interface? Do
> I use a class? Any other solution I am overlooking?
>
> Many thanks in advance for your advice.
>
> --
> Leo Breebaart  <[EMAIL PROTECTED]>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: perl better than python for users with disabilities?

2006-12-20 Thread Michele

What about indenting with a single space?
This does not seem a problem to me, even on tiny tiny screens =)

On 12/20/06, Dan Jacobson <[EMAIL PROTECTED]> wrote:


Can I feel even better about using perl vs. python, as apparently
python's dependence of formatting, indentation, etc. vs. perl's
"(){};" etc. makes writing python programs perhaps very device
dependent. Whereas perl can be written on a tiny tiny screen, and can
withstand all kinds of users with various disabilities, etc.?
Also perl is easier to squeeze into makefiles.

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

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

xor: how come so slow?

2008-10-15 Thread Michele
Hi,
I'm trying to encode a byte data. Let's not focus on the process of
encoding; in fact, I want to emphasize that the method
create_random_block takes 0.5s to be executed (even Java it's faster) on
a Dual-Core 3.0Ghz machine:

took 46.74679s, avg: 0.4674679s

Thus I suppose that the xor operation between bytes raise the execution
time to 0.5; why I suppose that?
Because in Python there's no support for bytes and even for xoring
bytes, so I used a workaround:
I cycle on the two strings to be xor-red
for every char in the strings
convert one char on integer and then xor them; (ord)
insert one char in the result, transforming the previous integer
in char (chr)

I suppose that ord() and char() are the main problems of my
implementation, but I don't know either way to xor two bytes of data
(bytes are represented as strings).
For more information, see the code attached.

How should I decrease the execution time? 

Thank you


from __future__ import division
import random
import time
import sha
import os

class Encoder(object):
def create_random_block(self, data, seed, blocksize):
number_of_blocks = int(len(data)/blocksize)
random.seed(seed)
random_block = ['0'] * blocksize
for index in range(number_of_blocks):
if int(random.getrandbits(1)) == 1:
block = data[blocksize*index:blocksize*index+blocksize]
for bit in range(len(block)):
random_block[bit] =
chr(ord(random_block[bit])^ord(block[bit])) # workaround per fare xor
bit a bit di str; xor e' solo supportato per int -> ord
return ''.join(random_block)


x = Encoder()
piece = os.urandom(1024*1024)
blocksize = 16384
t1 = time.time()
for l in range(100):
seed = random.getrandbits(32)
block = x.create_random_block(piece, seed, blocksize)
t2 = time.time()
print 'took ' + str(t2-t1) + 's, avg: ' + str((t2-t1)/100.0) + 's'
--
http://mail.python.org/mailman/listinfo/python-list


xor incongruences

2008-10-16 Thread Michele
Hi,
I write a simple encoder in python and Java; they do the same
computations, with the same inputs: however they won't produce the same
output.
Let me explain with code.

First of all, you need a test file for input:
$ dd if=/dev/urandom of=test.img bs=1048576 count=1

I have attached the code.
As you can see we have xor-red the same inputs (bitlists are the same,
thus the selected blocks to xor are the same - you can easily see it,
whenever a block is xor-red both programs will print out its hash).
But here comes the strange: the random_block that the
create_random_block function returns is not the same: in Java this block
has an hash which is different from the Python one.
Why?

Thank you
import os
import sha
import sys

class EncoderDecoder(object):
def create_random_block(self,piece,blocksize=16384):
if len(piece) % blocksize != 0:
raise Exception('size error')
self.N = len(piece)/blocksize
random_block = ['0']*blocksize
bitlist = [1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 
1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 
1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1]
for i in range(len(bitlist)):
if bitlist[i] == 1:
block = piece[i*blocksize:i*blocksize+blocksize]
print '%d-%d   %s' 
%(i*blocksize,i*blocksize+blocksize,sha.new(block).hexdigest())
for j in range(blocksize):
random_block[j] = chr(ord(random_block[j]) ^ ord(block[j]))
print sha.new(''.join(random_block)).hexdigest()
return ''.join(random_block)
   
if __name__ == '__main__':
data = open('test.img','rb').read()
x = EncoderDecoder()
x.create_random_block(data)
sys.exit(0)
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Test {
int N;

public byte[] create_random_block(byte[] piece)
throws NoSuchAlgorithmException, 
UnsupportedEncodingException {
N = piece.length / 16384;
byte[] random_block = new byte[16384];
int[] bitlist = { 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 
1, 1, 0,
0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 
1, 1, 1, 0, 0,
1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 
0, 1, 0, 0, 1,
0, 1, 0, 1 };
for (int i = 0; i < N; i++) {
if (bitlist[i] == 1) {
byte[] block = new byte[16384];
for (int j = 0; j < block.length; j++) {
block[j] = piece[i * 16384 + j];
}
System.out.println(i * 16384 + "-" + (i * 16384 
+ 16384)
+ "   " + 
AeSimpleSHA1.SHA1(block));
for (int j = 0; j < random_block.length; j++) {
random_block[j] = (byte) 
(random_block[j] ^ block[j]);
}
}
}
System.out.println(AeSimpleSHA1.SHA1(random_block));
return random_block;
}

public static void main(String[] args) throws IOException,
NoSuchAlgorithmException {
byte data[] = new byte[1024 * 1024];
FileInputStream fi = new FileInputStream("test.img");
fi.read(data);
Test x = new Test();
x.create_random_block(data);
System.exit(0);

}

public static class AeSimpleSHA1 {
private static String convertToHex(byte[] data) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; i++) {
int halfbyte = (data[i] >>> 4) & 0x0F;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9))
buf.append((char) ('0' + 
halfbyte));
else
buf.append((char) ('a' + 
(halfbyte - 10)));
halfbyte = data[i] & 0x0F;
} while (two_halfs++ < 1);
}
return buf.toString();
}

public static String SHA1(byte[] text) throws 
NoSuchAlgorithmException,
UnsupportedEncodingException {
MessageDigest md;
  

Interoperating with C

2008-10-18 Thread Michele
Hi there,
I would like to call C functions in a Python program, passing
user-defined objects and primitive python types (str, ints, etc.); of
course I also want to receive data from these functions, manipulating it
in my python program.
First of all: is this possible?
Secondly, what's the mapping between C types and Python types?

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


what's the python for this C statement?

2008-10-20 Thread Michele
Hi there,
I'm relative new to Python and I discovered that there's one single way
to cycle over an integer variable with for:
for i in range(0,10,1)

which is equivalent to:
for (i = 0; i < 10; i++)

However, how this C statement will be translated in Python?

for (j = i = 0; i < (1 << H); i++)

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


Problems with encoding/decoding locales

2008-09-30 Thread Michele
Hi there,
I'm using a python script in conjunction with a JPype, to run java classes.
So, here's the code:

from jpype import *
import os
import random
import math
import sys

input = open('foo.img','rb').read().decode('ISO-8859-1')

square = java.encoding(input)

output = java.decoding()

fd = open('foo_decode.img','wb')
fd.write(output.encode('ISO-8859-1'))
fd.close()
sys.exit(0)

First of all, java.encoding and java.decoding are two methods that
respectively take a java string as an argument and return a java String.
JPype is the bridge between Java and Python, and converts automatically
a str or unicode pythonstring into a Java String.
So, input and output are two unicode strings. I were forced to use
decode() and encode() methods by python, otherwise it refuses to read
foo.img file.
Here's the strange behaviour: when I write the output in the
'foo_decode.img', I don't reassemble the original file; I already tested
the java encoding/decoding libraries with the same input file, and what
the decoding process returns is the original file.
I suspect that the discrepancy is due to encoding/decoding of
ISO-8859-1: is that required?
What do you think about?

Thank you
   
   


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


md5 hash problems

2008-09-30 Thread Michele
Hi there,
why is this code generating a problem?

>>> input = open('foo.img','rb').read().decode('ISO-8859-1')
>>> import md5
>>> md5.new(input).hexdigest()
Traceback (most recent call last):
  File "", line 1, in 
UnicodeEncodeError: 'ascii' codec can't encode character u'\xdc' in
position 6:
ordinal not in range(128)
>>>

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


Re: Style question: metaclass self vs cls?

2012-07-17 Thread Michele Simionato
The standard is to use `cls`. In the __new__ method you can use `mcl` or `meta`.
-- 
http://mail.python.org/mailman/listinfo/python-list


surprising behaviour of global dictionaries

2012-10-09 Thread Michele Simionato
I have the following module implementing a registry of functions with a 
decorator:

$ cat x.py
registry = {} # global dictionary

def dec(func):
registry[func.__name__] = func
print registry, id(registry)
return func

if __name__ == '__main__':
import xlib
print registry, id(registry)

The library xlib just defines two dummy functions:

$ cat xlib.py
from x import dec

@dec
def f1():
pass

@dec
def f2():
pass

Then I get the following output:

$ python x.py
{'f1': } 27920352
{'f1': , 'f2': } 
27920352
{} 27395472

This is surprising since I would expect to have a single global dictionary, not 
two: how comes the registry inside the ``if __name__ == '__main__'`` block is 
different from the one seen in the library?

This is python 2.7.3 on Ubuntu.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: surprising behaviour of global dictionaries

2012-10-09 Thread Michele Simionato
On Tuesday, October 9, 2012 5:24:17 PM UTC+2, Peter Otten wrote:
> Seriously, you shouldn't use the main script as a library; it is put into 
> 
> the sys.modules cache under the "__main__" key. Subsequent imports under its 
> 
> real name will not find that name in the cache and import another instance 
> 
> of the module, with puzzling effects

Actually I usually never use the main script as a library, this is why I never 
experience this puzzling behavior before. But now it is clear, thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Testing against multiple versions of Python

2012-10-18 Thread Michele Simionato
Yesterday I released a new version of the decorator module. It should run under 
Python 2.4, 2.5, 2.6, 2.7, 3.0, 3.1, 3.2, 3.3. I did not have the will to 
install on my machine 8 different versions of Python, so I just tested it with 
Python 2.7 and 3.3. But I do not feel happy with that. Is there any kind of 
service where a package author can send a pre-release version of her package 
and have its tests run againsts a set of different Python versions?
I seem to remember somebody talking about a service like that years ago but I 
don't remembers. I do not see anything on PyPI. Any advice is welcome!

 Michele Simionato
   

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


Re: Testing against multiple versions of Python

2012-10-19 Thread Michele Simionato
ShiningPanda looks really really cool. I need to investigate it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Instrumenting a class to see how it is used

2012-05-14 Thread Michele Simionato
This may get you started (warning: not really tested).

$ echo instr.py
from warnings import warn

oget = object.__getattribute__
tget = type.__getattribute__

class Instr(object):

class __metaclass__(type):
def __getattribute__(cls, name):
clsname = tget(cls, '__name__')
warn('accessing %s.%s' % (clsname, name), stacklevel=2)
return tget(cls, name)

def __getattribute__(self, name):
warn('accessing %s.%s' % (self, name), stacklevel=2)
return oget(self, name)


Then change the base classes of the class you want to instrument, i.e.

class MyClass(MyBase) -> class MyClass(MyBase, Instr)

and see what happens. It should work in simple cases.
It will log a lot, so will have to adapt this.
-- 
http://mail.python.org/mailman/listinfo/python-list


A better contextlib.contextmanager

2012-05-23 Thread Michele Simionato
Python 3.2 enhanced contextlib.contextmanager so that it is possible to
use a context manager as a decorator. For instance, given the
contextmanager factory below

@contextmanager
def before_after():
print(before)
yield
print(after)

it is possibile to use it to generate decorators:

@before_after()
def hello(user):
print('hello', user)

This is equivalent to the more traditional

def hello(user):
with before_after():
print('hello', user)

but it has the advantage of saving a level of indentation and we all
know that flat is better than nested. Cool, but there are three issues:

1. I am using Python 2.7, not Python 3.2, so contextmanager has not such feature
2. The contextmanager decorator is losing the signature of the before_after 
factory:

   >>> help(before_after)

   Help on function before_after in module __main__:

   before_after(*args, **kwds)
3. before_after() decorators do not preserve the signature of the decorated 
function either.

Since I am the author of the decorator module I have easily found out a recipe 
to solve both issues. Here it is:

from decorator import decorator, FunctionMaker
from contextlib import GeneratorContextManager

class GeneratorCM(GeneratorContextManager):
def __call__(self, func):
return FunctionMaker.create(
func, "with _cm_: return _func_(%(shortsignature)s)",
dict(_cm_=self, _func_=func), __wrapped__=func)

@decorator
def contextmanager(func, *args, **kwds):
return GeneratorCM(func(*args, **kwds))

before_after() objects obtained by using this version of
contextmanager become signature-preserving decorators. I am not going
to explain how FunctionMaker performs its magic (hint: it uses eval),
but I am asking a question instead: should I add this feature to the
next release of the decorator module? Do people use the
context-manager-as-decorator functionality? It is quite handy in unit
tests and actually I think it came from the unittest2 module. But I am
reluctant to complicate the API of the module, which currently is
really really small and such has been for many years.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Argparse, and linking to methods in Subclasses

2011-07-18 Thread Michele Simionato
Here is an example by using my own library plac 
(http://pypi.python.org/pypi/plac):

class Server():
def configure_logging(self, logging_file):
pass
def check(self):
pass
def deploy(self):
pass
def configure(self):
pass
def __init__(self, hostname):
self.hostname = hostname

class SpamServer(Server):
def check(self):
pass

class HamServer(Server):
def deploy(self):
pass


def main(classname, hostname, methname): # add error checking at will
instance = globals()[classname](hostname)
getattr(instance, methname)()

if __name__ == '__main__':
import plac; plac.call(main)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's super() considered super!

2011-05-27 Thread Michele Simionato
On Friday, May 27, 2011 10:49:52 AM UTC+2, Ben Finney wrote:
> The exquisite care that you describe programmers needing to maintain is IMO
> just as much a deterrent as the super-is-harmful essay.

Worth quoting. Also I think this article may encourage naive programmers along 
the dark path of cooperative multiple inheritance, when they could instead use 
better designs.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's super() considered super!

2011-05-27 Thread Michele Simionato
The fact that even experienced programmers fail to see that
super(type(self),self) in Python 2 is NOT equivalent to super()
in Python 3 is telling something.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Class decorators might also be super too

2011-05-28 Thread Michele Simionato
He is basically showing that using mixins for implementing logging is not such 
a good idea, i.e. you can get the same effect in a better way by making use of 
other Python features. I argued the same thing many times in the past. I even 
wrote a module once (strait) to reimplement 99% of multiple inheritance without 
multiple inheritance, just to show that in can be done in few lines of code in 
a language as powerful as Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: multiprocessing shows no benefit

2017-10-20 Thread Michele Simionato
There is a trick that I use when data transfer is the performance killer. Just 
save your big array first (for instance on and .hdf5 file) and send to the 
workers the indices to retrieve the portion of the array you are interested in 
instead of the actual subarray.

Anyway there are cases where multiprocessing will never help, since the 
operation is too fast with respect to the overhead involved in multiprocessing. 
In that case just give up and think about ways of changing the original problem.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Let's talk about debuggers!

2017-10-25 Thread Michele Simionato
pdb plus plus: https://pypi.python.org/pypi/pdbpp
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Recommendation for Object-Oriented systems to study

2016-05-29 Thread Michele Simionato
On Sunday, May 29, 2016 at 4:42:17 PM UTC+2, Ankush Thakur wrote:
> Hello,
> 
> I'm a self-taught programmer who has managed to claw his way out of Python 
> basics and even covered the intermediate parts. But I feel I have a ton of 
> theory in my head and would like to see some smallish applications in action. 
> More specifically, I'm looking for Object Oriented designs that will help me 
> cement my knowledge and expose me to best practices that books never cover. I 
> have half a mind to start reading up the Django or Pandas source code, but I 
> don't want to overwhelm myself. 
> 
> Can somebody recommend smaller and simpler projects I can learn from? And if 
> I can pick the brains of the creator, bonus points!
> 
> Thanks in advance!
> 
> Ankush

Read the source code of the doctest module in the standard library.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: argparse and subparsers

2016-06-28 Thread Michele Simionato
I did not know about docopt. It is basically the same idea of this recipe I 
wrote about 12 years ago:

https://code.activestate.com/recipes/278844-parsing-the-command-line/?in=user-1122360

Good that it was reinvented :-)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Metaclasses, decorators, and synchronization

2005-09-26 Thread Michele Simionato

Michael Ekstrand ha scritto:
> One issue remains in this function: my method's signature is lost when
> synchronized is applied (at least as somemeth=synchronized(somemeth);
> I'm currently in a 2.3 environment that doesn't have the decorator
> syntax, but my understanding is that makes no difference). I've been
> able to preserve the doc string by setting the __doc__ attribute of the
> inner function before returning it, but is there a way to make this
> inner function appear to bear the same argument list as the original
> method? I've been poking around in new and inspect, but it is not
> appearing like an easy task.

It is not that easy, but you can leverage on my decorator module
which does exactly what you want:
http://www.phyast.pitt.edu/~micheles/python/decorator.zip

 Michele Simionato

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


Re: PEP 308 accepted - new conditional expressions

2005-09-30 Thread Michele Simionato
Terry Reedy ha scritto:

> "Dave Benjamin" <[EMAIL PROTECTED]> >
> > Hooray! After years of arguing over which syntax to use, and finally
> > giving up since nobody could agree,
>
> I understand that this has become the local 'politically correct' view, but
> as a participant in the discussion, I know it not true and actively
> deceptive.  The community was prevented from coming to a decision.  There
> was a 'primary' vote with an incumbent, 15 challengers, and several
> write-ins.  But there was no runoff.


FWIW, I think Terry's recollection is pretty close to the "historical
truth".
Guido could have decided two years ago, sparing us the PEP 308 ordalia.
So, I am happy that at the end we will have a conditional operator, but
I
am not happy of how the process worked out. It was just an enormous
waste
of resources that could have been employed much better :-(

Michele Simionato

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


how to send a SIGINT to a Python process?

2005-09-30 Thread Michele Simionato
Is there a way to send a SIGINT/KeyboardInterrupt to a
Python process (knowing the pid) that works both on Unix and Windows?

 Michele Simionato

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


Re: Feature Proposal: Sequence .join method

2005-09-30 Thread Michele Simionato
This can be shortened to

def interlace(x, i):
"""interlace(x, i) -> i0, x, i1, x, ..., x, iN
"""
i = iter(i)
i.next()
for e in i:
yield x
yield e

I have noticed a while ago that inside generators StopIteration is
automatically trapped, i.e.

def g():
yield 1
raise StopIteration
yield "Never reached"

only yields 1. Not sure if this is documented behavior, however, of if
it is an implementation
accident. Anybody who knows?

Michele Simionato

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


Re: epydoc, variables and encoding

2005-10-06 Thread Michele Petrazzo
Kenneth Pronovici wrote:
>> I found a "problem" on epydoc. If I specify an encoding, epydoc not
>> find my global variables, and if I remove it, it work well.

<-cut->

> 
> No, it's not normal, and I'm fairly sure it's a bug.

<-cut->

> Otherwise, you can try applying the following patch:
> 

<-cut->

> Maybe Edward won't like this patch, but since he seems to be
> unreachable for the last six months , you'll have to settle for
> my less-than-educated guess at a fix. :)

I don't know why Edward won't like this parch :), in any case it work
well for my source.

> 
> KEN
> 

Thanks,
Michele
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python recipes: list mixin, improved timeit, etc

2005-10-07 Thread Michele Simionato
Well, suppose you have a class MyObject and you want to add to it some
methods to make its instances into a database. You could put these
methods into another class called Storable (the mixin class).
Then you can mix MyObject with Storable and get what you want,
a class StorableObject inheriting both from Storable and MyObject.
Of course you can reuse Storable to make storable even other
classes, for  instance you could define a StorableOtherObject
inheriting from OtherObject and Storable.

Once in a time, I thought mixins where a good idea; now I don't think
so since they are too easily abused (see Zope 2) and as a consequence
you get spaghetti-inheritance, where you have objects with methods
inherited from everywhere. So be very careful if you want to use
mixins; often you can go without them.

Just my 2 Euro cents,

  Michele Simionato

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


Re: Python recipes: list mixin, improved timeit, etc

2005-10-07 Thread Michele Simionato
Paul Rubin wrote:
> Yeah, I wonder though how much of that is a result of Python's
> cavalier approach to multiple inheritance.  Does that happen much in
> CLOS?  In Java because of multiple interfaces?  I've studied Flavors a
> little and mix-ins were used in some extensive ways, but maybe
> programs using them required extra care.

I don't think Python approach to multiple inheritance is cavalier (you
may want
to clarify that statement). In CLOS multiple inheritance is less of a
problem
since (multi)methods are defined outside classes. One could argue that
using classes also as a scope-control mechanism (i.e. doing the job of
modules) is an abuse.

> The Python tutorial does caution against indiscriminate use of
> multiple inheritance.  I tried coding something without it, wished
> that I'd used it and did so in the next version, but still am not sure
> if I gained anything or not.

Nowadays I tend to use delegation via __getattr__ instead of multiple
inheritance.

Michele Simionato

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


Re: Can't extend function type

2005-10-07 Thread Michele Simionato
If you google a bit on the newsgroup, you should find a message
from me asking about the ability to subclass FunctionType, and
a reply from Tim Peters saying that the only reason why this
was not done is lack of developer time and the fact that this was
not considered an important priority.


 Michele Simionato

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


users of pycurl here?

2005-10-07 Thread Michele Simionato
I am having a hard time in finding out how to retrieve information
about
the *size* of files I want to download from an FTP site. Should I
send a QUOTE SIZE command to the ftp server or is there an easier way?
TIA,

  Michele Simionato

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


Re: users of pycurl here?

2005-10-10 Thread Michele Simionato
The Effbot wrote:
> here's a robust parser for various LIST output formats:
>
>http://cr.yp.to/ftpparse.html
>
> (google for "ftpparse" to find python bindings for that module)

Well, I have downloaded the one from your site (ftpparse-1.1-20021124)
and I have given a python setup.py install. Now I have a _ftpparse.so
which exposes a single function 'parse'. However both the module and
the function do not have any docstring,  the underscore makes me
believe that there should be a ftpparse.py file which is missing,
and the README says "for a usage example, see the sanity.py test
script" but there is not such a script in the distribution :-(

   Michele Simionato

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


Re: users of pycurl here?

2005-10-10 Thread Michele Simionato
Yes, it works fine, thanks (still I am a bit surprised there is not
ftpparse.py but only
an _ftpparse.so).

  Michele Simionato

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


Re: Batteries Included?

2005-10-11 Thread Michele Simionato
Mike Meyer:
> After you create a setup.py file for you program, doing
>
> "python setup.py bdist --formats=wininst"
>
> should do the trick.
>
> Of course, I don't own a Windows box, so I can't check it, but when I
> ask a setup file for help on formats, it tells me the wininst format
> is a windows installer.

I can confirm that it works (for pure Python applications), since I did
it.

   Michele Simionato

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


Re: Well written open source Python apps

2005-10-14 Thread Michele Simionato
> Could anyone suggest an open source project that has particularly well
> written Python?  I am especially looking for code that people would
> describe as "very Python-ic".

I vote for the "doctest" code in the standard library.

 Michele Simionato

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


example of using urllib2 with https urls

2005-10-18 Thread Michele Simionato
Can somebody provide an example of how to retrieve a https url, given
username and password? I don't find it in the standard documentation.
TIA,

  Michele Simionato

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


sort problem

2005-10-20 Thread Michele Petrazzo
I have a list of lists (a grid table) that can have about 15000 - 2
"rows" and 10 "cols", so:

1 [ [ 'aaa', 'vv', 'cc', 23, ... ],
2   [ 'aav', 'vv', 'cc', 45, ... ],
...
15000   [ 'sad', 'ad', 'es', 123, ... ], ]

I need to sort this list, but I need to specify two things: the "column"
and its type (string or int), so for example in this list, I want to
sort the fourth column that has int values. The type because that I want
that 1, 2, 12 will be sort in this order, not 1, 12, 2 like strings.

I have already tried to modify some code found on aspn, but the results
are always too slow for me, about 30-40 sec.
Can someone has some code or some point where can I start for speedup my
code?

Thanks,
Michele
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sort problem

2005-10-20 Thread Michele Petrazzo
Lasse Vågsæther Karlsen wrote:
> How about:
> 
> list.sort(key=lambda x: x[3])
> 
> Does that work?
> 

Yes, on my linux-test-box it work, but I my developer pc I don't have
the 2.4 yet. I think that this is a good reason for update :)

Thanks,
Michele
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sort problem

2005-10-21 Thread Michele Petrazzo
Kent Johnson wrote:
> or learn about decorate-sort-undecorate:
> 
> lst = [ ...whatever ] lst = [ x[3], i, x for i, x in enumerate(lst) ]
> 
I think that here the code must be changed (for the future):
lst = [ (x[3], i, x) for i, x in enumerate(lst) ]

> lst.sort() lst = [ x for _, _, x in lst ]


Wow, this work with my py 2.3!

> 
> Kent
> 

Thanks,
Michele
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python vs Ruby

2005-10-21 Thread Michele Simionato
Tom Anderson:
>> I have no idea what Scheme is, but I'll cettainly look it up as soon as
>> I'm done writing this.

> You won't like it. Give yourself another 5-10 years, and you might start
> to find it strangely intriguing. 

+1 ;-)


  Michele Simionato

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


Re: Python vs Ruby

2005-10-24 Thread Michele Simionato
Alex Martelli wrote:
> ... remember Pascal's "Lettres Provinciales",
> and the famous apology about "I am sorry that this letter is so long,
> but I did not have the time to write a shorter one"!-)

This observation applies to code too. I usually spend most of my time
in making short programs
that would have been long. This means:

cutting off non-essential features (and you can discover that a feature
is non essential only after having implemented it)

and/or

rethinking the problem to a superior level of abstraction (only
possible after you have implented
the lower level of abstraction).

 Michele Simionato

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


Re: Python vs Ruby

2005-10-24 Thread Michele Simionato
Alex Martelli:
> Michele Simionato:
>> cutting off non-essential features (and you can discover that a feature
>> is non essential only after having implemented it)

> This one is difficult if you have RELEASED the program with the feature
> you now want to remove, sigh.

Yeah, but I used the wrong word "features", which typically means "end
user features".
Instead, I had in mind "developer features", i.e. core features that
will be called later
in "client" code (I am in a framework mindset here).

Typically I start with a small class, then the class becomes larger as
I add features that will
be useful for client code, then I discover than the class has become
difficult to mantain.
So I cut the features and and I implement them outside the class and
the class becomes
short again.

However, I *cannot* know from the beginning what is the minimal set of
features
needed to make short the client code until I write a lot of client
code. I can make things short
only after I have made things long. I think this applies to me, to you,
to Pascal and to
everybody in general. It is impossible to start from the beginning with
the short program,
unless you already know the solution (that means, you have already
written the long
version in the past). Still, some naive people think there is a silver
bullet or an easy way
to avoid the hard work. They are naive ;)

Michele Simionato

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


Re: tool for syntax coloring in html

2005-10-26 Thread Michele Simionato
Gerhard wrote:
> http://initd.org/pub/software/pysqlite/doc/usage-guide.html

Can I suggest you to use a larger font for the code?It is pretty
difficult to parse with my
current screen resolution. BTW, pysqlite2 is pretty cool ;)

   Michele Simionato

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


Re: wxPython import error

2005-10-26 Thread Michele Petrazzo
[EMAIL PROTECTED] ha scritto:
> I have tried several times to install wxPython on Fedora Core 2.  The
> installation seems to go fine (from sources), but when I try to import the
> wx module I keep getting the following error:
> 

<-cut->

> Any help or explanation would be greatly appreciated.

For a my customer I had tried a lot of time, but without success to 
compile and install wx 2.6.x
But luckily there is a precompiled package on wxpython.org.
Have you try it?

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


Re: Web automation with twill

2005-11-04 Thread Michele Simionato
BTW, O'Reilly just published an article of mines on twill:

http://www.onlamp.com/pub/a/python/2005/11/03/twill.html

    Michele Simionato

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


Re: Web automation with twill

2005-11-04 Thread Michele Simionato
qwwwee:
> By the way, are you aware that C. Titus Brown (twill's author)
> tells "peste e corna" of Zope?

No, but I am not surprised.  I also say "peste e corna" of Zope ;)
In general I am an anti-frameworks guy (in good company with
many Pythonistas including Guido).

  Michele Simionato

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


Re: which feature of python do you like most?

2005-11-08 Thread Michele Simionato
> which feature of python do you like most?

It makes easy things easy, while keeping hard things possible.

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


Re: Installing Tkinter on knoppix

2005-11-09 Thread Michele Simionato
sudo apt-get install python2.4-tk

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


Re: web interface

2005-11-10 Thread Michele Simionato


I have been looking for an example like this for a while, so thanks to
J.P. Calderone.
Unfortunately, this kind of solution is pretty much browser-dependent.
For instance,
I tried it and it worked with Firefox, but not with MSIE 5.01 and it
will not work with any
browser if you disable Javascript. So, I don't think there is a real
solution
for this kind of problem as of today (I would love to be wrong,
though).

 Michele Simionato

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


Re: Tutorials for Python + PostgreSQL

2005-11-23 Thread Michele Simionato
Steve:
> I want to learn more about enterprise-level programming using Python
> and PostgreSQL. From what I've searched, it seems that psycho is
> interesting to improve runtime too. Do you have tutorials, articles and
> tips to learn this combination? I've been working with PostgreSQL for 2
> years, and with Python for 6 months.
> Thank you,

Since Psyco is meant to speedup Python code, whereas the psycopg
adapter is
C-coded, I strongly doubt you will get any improvement from the
combination. 

Michele Simionato

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


Re: super() and multiple inheritance

2005-12-02 Thread Michele Simionato
Hermy:
> So, for the moment my conclusion is that although Python has some
> syntax for multiple inheritance, it doesn't support it very well, and I should
> probably stick to single inheritance.

This is not much a problem of Python, the problem is that multiple
inheritance is
intrinsically HARD to support. If you can avoid it, avoid it. This will
probably make
your application more maintanable.

I your case, I would go with the keyword argument suggestion.

  Michele Simionato

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


Re: Favorite flavor of Linux? (for python or anything else)

2005-12-05 Thread Michele Simionato
I tried Kubuntu and Debian (in the trivial to install version known as
Knoppix/Kanotix)
and I like Debian more, but this is just me.

Michele Simionato

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


Re: Rebinding stdout (was: Re: Python! Is! Truly! Amazing!)

2005-01-03 Thread michele . simionato

Just wrote:
> In article <[EMAIL PROTECTED]>,
>  Simo Melenius <[EMAIL PROTECTED]> wrote:
>
> > I've sometimes replaced sys.stdout (and/or sys.stderr) to
> > capture/redirect debugging information in existing code that has
> > unwisely just "print"ed error and warning messages, instead of
using
> > sys.stderr or error logging modules.
> >
> > py> def with_output_to_string (func):
> > ... try:
> > ... sys.stdout = StringIO.StringIO ()
> > ... func ()
> > ... return sys.stdout.getvalue ()
> > ... finally:
> > ... sys.stdout = sys.__stdout__
>
> Aargh, I can't believe how widespread this idiom is :-(. See my other
> reply in this thread: DON'T use sys.__stdout__. Ever.
> 
> Just

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


Re: Rebinding stdout (was: Re: Python! Is! Truly! Amazing!)

2005-01-03 Thread michele . simionato
(Not sure if my other message arrived)

I am guilty of using this idiom, too.

The standard library
http://www.python.org/dev/doc/devel/lib/module-sys.html#l2h-396

says:

"""
__stdin__
__stdout__
__stderr__
These objects contain the original values of stdin, stderr and
stdout at the start of the program. They are used during finalization,
and could be useful to restore the actual files to known working file
objects in case they have been overwritten with a broken object.
"""

Notice the "during finalization" sentence.
Maybe you should change the doc and explain what __stdout__ is intended
for?

Michele Simionato

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


Re: Frameworks for "Non-Content Oriented Web Apps"

2005-01-04 Thread michele . simionato
Well, with your first post you managed to get a very unclear picture of
what you mean by "non-content oriented Web Application" ;-)

Judging from your following posts, you want an easy way to construct
Web interfaces, i.e. forms. This can be done with any Web framework,
but a typical Web framework provides a lots of content-related
functionality
you don't want. For instance you could use Plone for your task, but you
would waste 99% of its functionality and it would be absolutely
overkill.

If I had to write a Web application such as Webmin, for instance, i.e.
one that use a Web interface to manage other applications, I would
use Quixote as my Web framework of choice. Its key points are
simplicity and the fact that it provides *very little*. Just the form
library would be enough for you. Since the different part of Quixote
are well separated, the learning curve is really really small.

It also takes a little time to evaluate it. I suggest you to give a
look
at it.


    Michele Simionato

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


Re: Python evolution: Unease

2005-01-04 Thread michele . simionato
Maybe a PSF grant would help? I guess this has been considered ...
Michele Simionato

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


Re: The Industry choice

2005-01-04 Thread michele . simionato
But then I have THREE published recipes!!
Does that mean that I get three free copies of the cookbook ? ;-)
Michele

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


Re: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30)

2005-01-04 Thread michele . simionato
Holger:

> FWIW, i added the recipe back to the online cookbook. It's not
perfectly
> formatted but still useful, i hope.

>   http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/361742

Uhm... on my system I get:

>>> german_ae = unicode('\xc3\xa4', 'utf8')
>>> print german_ae # dunno if it will appear right on Google groups
ä

>>> german_ae.decode('latin1')
Traceback (most recent call last):
File "", line 1, in ?
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in
position 0: ordinal not in range(128)
?? What's wrong?

Michele Simionato

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


Re: Python evolution: Unease

2005-01-04 Thread michele . simionato
Aahz:

> The first three PSF grants were all in some way not directly related
to
> changing the core language. One was for a library, one for improving
> Jython, and one for improving docs. Giving the PSF more money
increases
> the chances for additional work.

Here is the link you forgot to post ;-)

http://www.python.org/psf/grants/

The one about the docs seems more about teaching scientists how to use
Python.

   Michele Simionato

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


Re: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30)

2005-01-04 Thread michele . simionato
Yep, I did the same and got confused :-/

Michele

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


Re: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30)

2005-01-04 Thread michele . simionato
Stephan:

> I'd rather use german_ae.encode('latin1')
^^
> which returns '\xe4'.

uhm ... then there is a misprint in the discussion of the recipe;
BTW what's the difference between .encode and .decode ?
(yes, I have been living in happy ASCII-land until now ... ;)
I should probably ask for an unicode primer, I have found the
one by Marc André Lemburg
http://www.reportlab.com/i18n/python_unicode_tutorial.html
and I am reading it right now.


 Michele Simionato

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


Re: Python evolution: Unease

2005-01-04 Thread michele . simionato
Paul Rubin:
> I'm now running the Python
> that was included in Fedora Core 3 GNU/Linux, a complete OS distro on
> a DVD-ROM, containing about 3 gigabytes not including sources. And
> when a user installs 3 gigabytes of software from a DVD, they can
> reasonably expect that they've installed a complete system and
> shouldn't need to download anything additional to use all the
features
> of the programs on the DVD. Now the Fedora maintainers aren't Python
> gurus--people ask for Python so they did the obvious thing:
downloaded
> it, ran its installer, put the output into their distro, and said
"ok,
> Fedora has Python". That's all they should need to do to incorporate
> Python into Fedora. So it's up to the Python maintainers, not the
> Fedora maintainers or the user, to make sure that the Python distro
> has everything that users need, without further downloading.

Dunno about Fedora, I stopped using Red Hat just because they were
*not* using
the standard Python distribution, and the version they shipped was
cripped  in various
ways. There is nothing the Python developers can do if the OS vendors
choose to ship
modified Python distributions, with missing modules or splitted in n
separated packages
to download separately.

   Michele Simionato

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


Re: Python evolution: Unease

2005-01-05 Thread michele . simionato
John Roth:
> The bottom line is that I'm not going to be writing any
> extensive pieces of Python documentation. My time
> is better spent elsewhere.

Well, a couple of years ago I realized that some documentation on the
MRO
was missing. I wrote a document in reST, posted here, and Guido put it
on
python.org. It was as easy as it sounds. So I don't see your problem.

Dave Kulhman wrote some utility to convert reST in latex using the same
style of the standard library docs; I haven't used it myself, but you
may check
with him: http://www.rexx.com/~dkuhlman/

P.S. since you cite descriptors, what's wrong with Raimond Hetting
documentation?
http://users.rcn.com/python/download/Descriptor.htm

The only problem I see is that it is not integrated with the official
docs, but this is a
minor issue, I think.


 Michele Simionato

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


Re: Python evolution: Unease

2005-01-05 Thread michele . simionato
Did you used Tkinter and Tix? Most of my problems were there.
Of course, I also got in trouble when upgrading to Python 2.2 from
1.5.2
Finally they switched to Python 2.2, but at that moment Python 2.3 came

out and I got tired. I switched to Mandrake 1.5 and I am happy with it.

Never had any serious trouble with urpmi and lots of Python packages
are
available.


 Michele Simionato

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


Re: python-dev Summary for 2004-11-16 through 2004-11-30

2005-01-06 Thread michele . simionato
> Would you like the source with your function?

Yes, since I asked for this feature something like two years ago ;-)
Michele Simionato

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


Re: parameterized metaclass (or metametaclass)

2005-01-06 Thread michele . simionato
> I was wondering if there is some simpler way of building
parameterized
> metaclasses ?

Why not just a function returning metaclasses?

def metaFactory(*args):
dic = 
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

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


Re: python3: 'where' keyword

2005-01-07 Thread michele . simionato

> But we're talking about the mythical/hypothetical Python 3, so maybe
> there's a chance of fixing the scoping rules, which it seems to me
are
> currently pretty badly broken.

I don't think the current scoping rules will be changed in Python 3.0.
I can't give you the link right now, but there are threads about the
scope rules in
python-dev, with various people protesting and Guido saying that he
wants to 
keep them as they are.

 Michele Simionato

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


Re: "A Fundamental Turn Toward Concurrency in Software"

2005-01-08 Thread michele . simionato
>  So I've always had it in
> the back of my mind that languages that can easily support massive
> (especially automatic) parallelization will have their day in the
sun,
> at least someday.

and the language of the future will be called ... FORTRAN!

:-)

(joking, but it is the only language I know supporting massive
parallelization ...)


Michele Simionato

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


Re: Returning same type as self for arithmetic in subclasses

2005-01-08 Thread michele . simionato
Max. M.:
> So I wondered if there was a simlpler way to coerce the result into
my
> desired types rather than overwriting the __add__, __sub__ etc.
methods?

Tim Peters:
>> Generally speaking, no. But I'm sure someone will torture you with a
>> framework that purports to make it easy .

I will not dispute the Timbot assessment ;) He is also right that
people have
already undergone under this level of torture:  see
http://tinyurl.com/6m373
for instance.

   Michele Simionato

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


readline, rlcompleter

2005-01-10 Thread michele . simionato
This a case where the documentation is lacking. The standard library
documentation
(http://www.python.org/dev/doc/devel/lib/module-rlcompleter.html) gives
this example
try:
import readline
except ImportError:
print "Module readline not available."
else:
import rlcompleter
readline.parse_and_bind("tab: complete")

but I don't find a list of recognized key bindings. For instance, can I
would
like to bind shift-tab to rlcompleter, is that possible? Can I use
function
keys? I did various attempt, but I did not succed :-(
Is there any readline-guru here with some good pointers?
Michele Simionato

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


Re: Python & unicode

2005-01-11 Thread michele . simionato
Uhm ...

>>> class C(object):
... pass
...
>>> setattr(C, "è", "The letter è")
>>> getattr(C, "è")
'The letter \xe8'

;-)

   Michele Simionato

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


Re: Securing a future for anonymous functions in Python

2005-01-11 Thread michele . simionato
Jacek:
> Given a population with previous exposure to computer programming, my
> money is on the map-lambda version. But this last point is mostly
> irrelevant. The fact is that you cannot program computers without
> doing a bit of learning ... and the lambda, map and friends really do
> not take any significant learning.

This kind of "sociological" study would be pretty interesting to me ;-)

Personally, I find out that my mind manage pretty well one-level of
indirection
at time, not two. Consider for instance

def add1(x): return x+1
map(add1, mylist)

Here there are *two* levels of indirection:

first, I need to define add1;
second I need to translate mentally map to a loop.

Using lambda does not help:

map(lambda x: x+1, mylist)

still would require two levels for me, one to recognize the lambda
and one to convert map to a loop.

This is too much for me, so I just write

[x+1 for x in mylist]

where everything is explicit (or if you wish, I have just to recognize
that there
is a loop going on, pretty easy).

However, if I can skip a level of indirection (i.e. I do not need to
define
a function) I just prefer map:

map(int, mylist)

is simpler for me than

[int(x) for x in mylist]

since the latter introduces an useless x (which is also polluting my
namespace,
but this not my point, I could use a generator-expression instead).

So, in practice, I only use map with built-in or with predefined
functions, i.e. functions
which are already there for some other purpose; I do not like to be
forced to write a
function (or a lambda) for the only purpose of using map (at least in
Python).

Incidentally, I am not fond of the name "lambda" too. "fn", as Paul
Graham says,
looks much better.

What I would like, in Python, is some facility to manage callbacks in
the standard
library, then I would live pretty well without lambdas.
Just IMHO, YMMV, etc.

  Michele Simionato

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


Re: Python & unicode

2005-01-11 Thread michele . simionato
I forgot to add the following:

>>> setattr(C, "è", u"The letter è")
>>> getattr(C, "è")
u'The letter \xe8'
>>> print getattr(C, "è")
The letter è

Python identifiers can be generic strings, including Latin-1
characters;
they cannot be unicode strings, however:

>>> setattr(C, u"è", "The letter è")
Traceback (most recent call last):
File "", line 1, in ?
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in
position 0: ordinal not in range(128)

So you are right after all, but I though most people didn't know that
you can have
valid identifiers with accented letters, spaces, and non printable
chars.

> setattr(C, " ", "this works")
> getattr(C, " ")


Michele Simionato

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


python and macros (again) [Was: python3: 'where' keyword]

2005-01-11 Thread michele . simionato
Paul Rubin wrote:
> How about macros? Some pretty horrible things have been done in C
> programs with the C preprocessor. But there's a movememnt afloat to
> add hygienic macros to Python. Got any thoughts about that?

"Movement" seems quite an exaggeration. Maybe 2-3 people made some
experiments, but nobody within the core Python developers seems
to be willing to advocate the introduction of macros.

> Why should you care whether the output of a macro is ugly or not,
> if no human is ever going to look at it?

But at least some human eye have to look at it!

Did you ever debug a macro?


More seriuosly, I have given some thought to the issue, and I am very
much against the introduction of macros in Python.

Here are a few reasons:

1. I like defmacro in Lisp. Problem is, Lisp is an s-expression based
language, Python is not. We cannot implement defmacro in Python and
even if we could, if would be too ugly to be used (at least, IMHO).

2. One could proposed hygienic pattern-matching macros in Python,
similar to
Scheme syntax-rules macros. Again, it is not obvious how to
implement pattern-matching in Python in a non-butt-ugly way. Plus,
I feel hygienic macros quite limited and not worth the effort.

3. We would add to Python the learning curve of macros and their
subtilities and we do not want it.

4. Macros would complicate a lot Python module system.

5. We have Guido providing a good syntax for us all, why we should be
fiddling with it? More seriously, if some verbosity is recognized
in the language (think to the "raison d'etre" of decorators, for
instance) I very much prefer to wait for Guido to take care of
that, once and for all, than having 100 different custom made
solutions based on macros.

I am sure I could find other reasons if I think a bit more, but these
should suffice for the moment ;)

What I would be interested in is a Lisp/Scheme implementation
compiling to Python bytecode, but I am not aware of any project
in that direction.


Michele Simionato

P.S. some pointers for people interested on the topic:

http://logix.livelogix.com/ (a Python-like language with macros)
https://sourceforge.net/projects/pymac/ (an experimental
Dylan-inspired macro system for Python)

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


Re: Python & unicode

2005-01-11 Thread michele . simionato
Kent:
> I don't think so. You have hacked an attribute with latin-1
characters in it, but you
> haven't actually created an identifier.

No, I really created an identifier. For instance
I can create a global name in this way:

>>> globals()["è"]=1
>>> globals()["è"]
1

> According to the language reference, identifiers can only contain
letters a-z and A-Z,
> digits 0-9 and underscore.
>http://docs.python.org/ref/identifiers.html

The parser has this restriction, so it gets confused if it finds "è".
But the underlying
implementation just works for generic identifiers.
Michele Simionato

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


Re: python and macros (again) [Was: python3: 'where' keyword]

2005-01-11 Thread michele . simionato
Paul Rubin:
> [EMAIL PROTECTED] writes:

>> 

> It wasn't obvious how to do it in Scheme either. There was quite
> a bit of head scratching and experimental implementation before
> there was consensus.

Actually I am not convinced there is consensus yet, i.e. there is a
non-negligible minority of schemers convinced that original Lisp
macros where better, not to talk of common lispers ;)

>> 3. We would add to Python the learning curve of macros and their
>> subtilities and we do not want it.

> I can't imagine how it could be worse than the learning curve of
> __metaclass__, which we already have.

To me, learning macros *and their subtilities* was much more difficult
than learning metaclasses.

>> 4. Macros would complicate a lot Python module system.

> I don't see how, but maybe I'm missing something.

Go to comp.lang.scheme and google for "macros and module system";
you will get everything you want to know and much more!

>> 5. We have Guido providing a good syntax for us all, why we should
be
>> fiddling with it? More seriously, if some verbosity is recognized
>> in the language (think to the "raison d'etre" of decorators, for
>> instance) I very much prefer to wait for Guido to take care of
>> that, once and for all, than having 100 different custom made
>> solutions based on macros.

> Every time some newbie asks an innocent "how do I ..." question, we
> see unbelievably horrid answers from gurus. Just check the FAQ about
> conditional expressions, etc. I just don't see Python syntax changes
> as forthcoming.

Well, I see this as a positive fact. If a syntax is contrived (such as
a ternary
operator, for instance) it is better *not* to have it than to have one
hundred custom
made syntaxes. At the end, we are just talking about syntax sugar here,
not about
lack of functionality.

>> What I would be interested in is a Lisp/Scheme implementation
>> compiling to Python bytecode, but I am not aware of any project
>> in that direction.

> But that sounds like a bizarre idea. Python bytecode is just a
> CPython artifact, not part of the language. And it's not even that
> good an artifact. Good Lisp/Scheme implementations compile to native
> code that beats the pants off of CPython bytecode. It would make much
> more sense to have a Python implementation that compiles Python to
> S-expressions and then lets a high performance Lisp or Scheme system
> take care of the rest.

This is a bizarre idea if you want to make Python run faster. It is not
so bizarre
if what you want is to have access to Python from Lisp/Scheme in the
same sense 
Jython has access to Java.


 Michele Simionato

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


Re: "private" variables a.k.a. name mangling (WAS: What is print? A function?)

2005-01-25 Thread michele . simionato
>Name mangling is there to keep you from accidentally hiding such an
>attribute in a subclass, but how often is this really a danger? Can
>someone give me an example of where __-mangling really solved a
problem
>for them, where a simple leading underscore wouldn't have solved the
>same problem?

Look at the "autosuper" implementation on Guido's descrintro paper;
there the
fact that you user __super instead of _super is essential.

However I have written tens of thousands of lines of Python code and
never
needed __protected variables except in a few experimental scripts for
learning purpose. So I agree that the need does not occur often, but it
is still an useful thing to have.
Michele Simionato

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


FTP Server

2005-01-26 Thread michele . simionato
What's the simplest way to write an FTP Server in Python?
A short research on the newsgroup and on the Cookbook did not
bring out anything relevant (but I hear a little voice in the
back of my head saying Twisted, Twisted! ...)
Michele Simionato

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


Re: FTP Server

2005-01-26 Thread michele . simionato

Do you have a code snippet/pointer so I have an idea of how to use it?
M.S.

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


Re: FTP Server

2005-01-26 Thread michele . simionato
> If you're after a simple FTP server, have a look at medusa.
Uhm ... Medusa does not seem actively maintained nowadays.

  M.S.

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


Re: python without OO

2005-01-27 Thread michele . simionato
Davor wrote:
> Thanks,
>
> I do not hate OO - I just do not need it for the project size I'm
> dealing with - and the project will eventually become open-source and
> have additional developers - so I would prefer that we all stick to
> "simple procedural" stuff rather than having to deal with a developer
> that will be convincing me that his 50 layers inheritance hierarchy
is
> good since it exists in some weird pattern that he saw somewhere on
> some Java design patterns discussion board :-) and other "proper" OO
> design issues... Once I opted for C++ in a very small project and
> believed everyone will stick with C subset + better type checking
> offered through C++ - but I simply could not manage to keep them off
> using OO stuff which was just making program more complicated than it
> should have been. (note, I am not an experienced developer, nor the
> others I'll be working with (even though some think they are:-)), so
I
> prefer preemptively dealing with issue of everyone showing off their
OO
> design skills)
>

I think Davor is making an important point here: Python has grown in
the last 14 years, and it is no more the simple scripting language
it used to be. In particular, it evolved a lot of OOP "cruft"
(static/classmethods, properties, the __new__ method, super, the new
MRO, descriptors,metaclasses, etc.) and there is more than a learning
curve issue coming with the added complexity. Davor is right: even if
you do not want to use it, the stuff is *there* and somebody in your
team will. So definitely there is an audience of programmers that just
do not have an use for all the sophistication and actually are
penalized by it.

There is not much than can be done at the Python level. But I would
see with interest a Python spinoff geared towards simplicity. Few
months ago there was the Prothon proposal (by all means a terrible
proposal) but the goal that motivated it (simplification, trying
to remove classes) was in my opinion worthwhile.

Now, *how* to remove (or simplify) classes is not at all clear to me,
not I am convinced that prototypes are the right way to go, but still I
feel that there is something wrong with inheritance. Maybe
protocols are the solution, who knows? But in any case I think it
is important to keep searching for semplicity. I do not believe
Python is the definitive language, and it is probabily possible
to introduce something better. It is just that nothing of the
kind appeared until now, but I keep watching at the horizon ;)
Michele Simionato

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


Re: python without OO

2005-01-27 Thread michele . simionato
Peter Maas:
>[EMAIL PROTECTED] schrieb:

>> Davor is right: even if
>> you do not want to use it, the stuff is *there* and somebody in your
>> team will. So definitely there is an audience of programmers that
just
>> do not have an use for all the sophistication and actually are
>> penalized by it.

>No, because Python does not enforce using advanced concepts. You
>can write programs that are as simple as in 1991. A group of
developers
>always has to find some kind of common style with a chance that some
>are penalized. This can happen with every language.

No. In theory C++ could be kept as simple as C but in practice it is
not.

>> There is not much than can be done at the Python level. But I would
>> see with interest a Python spinoff geared towards simplicity.

>I think this would be useless because advanced concepts exist for
>a reason. A simplified spin-off would aquire advanced concepts
>over time and would just become a clone of Python.

And then we will need another simplified spinoff ;)
There is always a fight between simplificity and complexity.
Some complexity is not needed, and I am sure even in Python
something could be dropped. But it is difficult to find what can
be removed. Remember that Saint-Exupery quote? Something
like "a work of art is finished when there is nothing left to remove?"
M.S.

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


Re: python without OO

2005-01-27 Thread michele . simionato
> "Perfection is achieved, not when there is nothing more to add, but
> when there is nothing left to take away."

Thanks, that was it! ;)

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


Re: future of computing languages

2005-01-30 Thread Michele Simionato
I found that page very shallow and superficial. What they
call "the language of the future" is actually the language
of the present. Python (but also, Ruby, Perl, Smalltalk, Lisp,
Scheme, ...) have already most of the features they list.

Then they claim "the language of the future will be so
different from the languages we have now that we cannot
imagine how it will be". This is pretty naive. A Lisper would
say that nothing new happened in the last 40 years.

Actually, I think that something new happened, but not that much.
The progress was more in the technology than in the
programming paradigms. I mean, OO was already there
in Simula. It this very possible that the language of 2045
will not be very different from the current dynamic languages.

The all page reminds me of the excitation of 60's about the
space program (affirmations such "in the year 2000 we will
have colonies on Mars") We all know how it ended :-(
Michele Simionato

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


Popularizing SimpleHTTPServer and CGIHTTPServer

2005-02-02 Thread Michele Simionato
Just submitted a recipe with this goal in mind:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/365606
Michele Simionato

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


Re: new style exception handleing

2005-02-03 Thread Michele Simionato
Google is your friend.
This has been discussed a lot in the past. For instance, google for the
thread,
"Exceptions as New Style Classes", there was also a PEP by Steven
Taschuk,
IIRC.

      Michele Simionato

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


Re: advice needed for simple python web app

2005-02-03 Thread Michele Simionato
Dan Perl:
> The application is just something I'm playing with to learn a little
bit on
> web apps.  It uses an HTML form to send an email.  The form takes
inputs
> like the From:, To: and Subject: fields and a text field.

It is difficult to beat CGI + CGIHTTPServer for conceptual simplificity
and easy of use: however, Quixote comes close and it has a *much*
better support for forms. Here is an
example from the minidemo in the distribution, so you have an idea of
how the code looks
like:

> from quixote.publish import Publisher
> from quixote.directory import Directory

> class RootDirectory(Directory):

>_q_exports = ['', 'hello']

>def _q_index(self):
>return '''
>Welcome to the Quixote demo.  Here is a
>link.
>
>  
>'''

>def hello(self):
>return 'Hello world!'


> def create_publisher():
>return Publisher(RootDirectory(),
> display_exceptions='plain')


> if __name__ == '__main__':
>from quixote.server.simple_server import run
>print 'creating demo listening on http://localhost:8080/'
>run(create_publisher, host='localhost', port=8080)

The exported methods of your directory class corresponds to Web pages;
_q_index
returns the main page, hello an hello word page. This works out of the
box with
no configuration at all, you don't need to create a cgi-bin directory,
nothing.
It is trivial to replace simple_server with a more serious server
(twisted_server,
scgi_server, etc. )

Notice: this example works in Quixote 2.0 which is currently in alpha.
Don't let
the "alpha" scares you: that means that the documentation is still a
bit rough and
few things are not fully settled down, but the framework is very much
usable.


  Michele Simionato

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


Re: ANN: PyDev 0.9.0 released

2005-02-04 Thread Michele Petrazzo
Fabio Zadrozny wrote:
Hi All,
PyDev - Python IDE (Python development enviroment for Eclipse) version 
0.9.0 has just been released.

This release supports python 2.4 and has PyLint 0.6 integrated.
Code completion had some improvements too.
Check the homepage for more details (http://pydev.sourceforge.net/).
Regards,
Fabio Zadrozny
--
Software Developer
ESSS - Engineering Simulation and Scientific Software
www.esss.com.br
This page on your site, don't exist!
http://pydev.sourceforge.net/Features.html
modify the link in:
http://pydev.sourceforge.net/features.html
Bye,
Michele
--
http://mail.python.org/mailman/listinfo/python-list


making symlinks with distutils

2005-02-04 Thread Michele Simionato
I want to distribute a pure Python package with this structure:

>mypackage
> __init__.py
> module1.py
> module2.py
> ...
> myexecutable.py

In particular, myexecutable.py is a script which is intended to be used
from the command line via the shebang trick. I want to distribute on
Unices.
and I want a symlink

/usr/bin/myexecutable -> /mypackage/myexecutable.py

to be made at installation time, when the user runs "python setup.py
install".

What is the recommanded way to do that? Do I need a postinstallation
script or something like that?

I could do that in various way, but I don't see the obvious one,
maybe because I am not a Dutch ;)


 Michele Simionato

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


Re: making symlinks with distutils

2005-02-04 Thread Michele Simionato
>From what I see in the docs, registering a script just normalize the
shebang line, but does not install it in
/usr/bin, nor make any symbolic links, so it is not
what I am looking for.
I guess I need to add a os.link(src, dst) somewhere in the
setup.py script or in a postinstallation script but I am not exactly
sure where.

 M.S.

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


Re: making symlinks with distutils

2005-02-04 Thread Michele Simionato
Sylvain Thenault:
> Actually it does install it is $PREFIX/bin.

Aha! And how do I set $PREFIX? Is it a Unix environment variable or is
it
a keyword argument in setup? Something like setup( prefix="/usr") ?

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


Re: Why is there no instancemethod builtin?

2005-06-19 Thread Michele Simionato
In this case I have used hasattr(obj, "__iter__") instead of
isinstance(obj, list)
(strings are iterable but do not have __iter__ method). I think hasattr
is much better
since it works for tuples and custom iterables too.

      Michele Simionato

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


Re: Why is there no instancemethod builtin?

2005-06-19 Thread Michele Simionato
I think strings do not have __iter__ on purpose, exactly to distinguish
them
from other iterables, since sometimes it is nice to consider them
atomic,
but I am not sure of this. You should ask the developers. Anyway, the
right definition of iterable is (as I was told) "an object X such that
iter(X)
does not throw an exception". Objects following the __getitem__
protocol
- such as strings -are iterables even if they do not have an __iter__
method.


       Michele Simionato

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


Re: "static" data descriptors and possibly spurious calls to __set__?

2005-06-19 Thread Michele Simionato
>...it's this last one that causes the problem. In the real code, the
>call to type.__setattr__ referred to above seems to lead to a call to
>something like cls.__base__.__dict__[attr].__set__(cls, value).

Uhm ... sounds right, but I a bit confused. Could you please give us a
doctest showing us what you get and what you would like to get?

   Michele Simionato

  Michele Simionato

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


Re: Create our own python source repository

2005-06-21 Thread Michele Simionato
qwwee:
> for a certain argument I'd prefer an application fully
>explained (also if not covering all the features) to a more general
>tutorial with only brief and unrelated code snippets.
>Unfortunately, that's not the way things are normally done, because it
>is much harder to build a useful application and fully comment it

A part the Cookbook, I know of at least two Python books taking the
approach you describe:

1. Dive into Python (Pilgrim)
2. Programming Python (Lutz)

Dive into Python is free (and even translated in Italian on
www.python.it, IIRC)

  Michele Simionato

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


Re: Lisp development with macros faster than Python development?..

2005-07-06 Thread Michele Simionato
Fuzzyman:
> So Lisp is for really good programmers, and Python is for
> mediocre programmers ?


Python is *also* for mediocre programmers. I see this as a
strength, not as a weakness.

  Michele Simionato

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


Re: Web-Forms

2005-07-22 Thread Michele Simionato
Use twill:http://www.idyll.org/~t/www-tools/twill.html

Michele Simionato

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


Re: multiple inheritance super()

2005-07-27 Thread Michele Simionato
>I am mostly
>using old style (without type unification) init but this motivate the
>shift for the new style. Is there somewhere a document about this?

Yes, see http://www.python.org/2.3/mro.html by yours truly

   Michele Simionato

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


  1   2   3   4   5   6   7   8   9   10   >