Re: Python object overhead?

2007-03-24 Thread Felipe Almeida Lessa
On 3/23/07, Bjoern Schliessmann
[EMAIL PROTECTED] wrote:
 (Note that almost everything in Python is an object!)

Could you tell me what in Python isn't an object? Are you counting
old-style classes and instances as not objects?

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


Re: functions, classes, bound, unbound?

2007-03-24 Thread Felipe Almeida Lessa
On 24 Mar 2007 20:24:36 -0700, 7stud [EMAIL PROTECTED] wrote:
 Here is some example code that produces an error:
[snip]

Why do people absolutely *love* to do weird and ugly things with
Python? Contests apart, I don't see lots of people trying this kind of
things on other (common) languages.

Say with me: Python is powerful, but I'll use that power *only* for
beautiful and straightforward code.

Further reading:
http://www.python.org/doc/Humor.html#zen

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


Re: Can I reverse eng a .pyc back to .py?

2007-02-20 Thread Felipe Almeida Lessa
On 2/19/07, Steven W. Orr [EMAIL PROTECTED] wrote:
 The short story is that someone left, but before he left he checked in a
 .pyc and then both the directory was destroyed and the backups all got
 shredded (don't ask*). Is there anything that can be extracted? I looked
 on the web and the subject seems to get different answers, all old.

Only for .pyc's of Python versions upto 2.3:
http://packages.debian.org/unstable/python/decompyle

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


Re: help on packet format for tcp/ip programming

2007-02-07 Thread Felipe Almeida Lessa
On 7 Feb 2007 19:14:13 -0800, [EMAIL PROTECTED] [EMAIL PROTECTED]
 struct module pack and unpack will only work for fixed size buffer :
 pack('1024sIL', buffer, count. offset) but the buffer size can vary
 from one packet to the next  :-(

Then send the size of the buffer before the buffer, so the recipient
can expect that many bytes.

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


Re: maximum number of threads

2007-01-10 Thread Felipe Almeida Lessa
On 1/10/07, Gabriel Genellina [EMAIL PROTECTED] wrote:
 At Wednesday 10/1/2007 04:38, Paul Sijben wrote:
 Does anyone know what it going on here and how I can ensure that I have
 all the threads I need?

 Simply you can't, as you can't have 1 open files at once.
 Computer resources are not infinite.
 Do you really need so many threads? Above a certain threshold, the
 program total execution time may increase very quickly.

Maybe Stackless could help the OP?
http://www.stackless.com/

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


Re: maximum number of threads

2007-01-10 Thread Felipe Almeida Lessa

On 1/10/07, Laurent Pointal [EMAIL PROTECTED] wrote:

This is a system configurable limit (up to a maximum).

See ulimit man pages.

test

ulimit -a

to see what are the current limits, and try with

ulimit -u 2000

to modify the maximum number of user process (AFAIK each thread use a
process entry on Linux)


I don't think it's only this.

---
$ ulimit -a
core file size  (blocks, -c) 0
data seg size   (kbytes, -d) unlimited
max nice(-e) 20
file size   (blocks, -f) unlimited
pending signals (-i) unlimited
max locked memory   (kbytes, -l) unlimited
max memory size (kbytes, -m) unlimited
open files  (-n) 1024
pipe size(512 bytes, -p) 8
POSIX message queues (bytes, -q) unlimited
max rt priority (-r) unlimited
stack size  (kbytes, -s) 8192
cpu time   (seconds, -t) unlimited
max user processes  (-u) unlimited
virtual memory  (kbytes, -v) unlimited
file locks  (-x) unlimited
---

Well, unlimited number user processes. But:

---
$ python test.py
50
100
150
200
250
300
350
Exception raised: can't start new thread

Biggest number of threads: 382
---

The test.py script is attached.

--
Felipe.
from thread import start_new_thread
from time import sleep

def sleeper():
	try:
		while 1:
			sleep(1)
	except:
		if running: raise

def test():
	global running
	n = 0
	running = True
	try:
		while 1:
			start_new_thread(sleeper, ())
			n += 1
			if not (n % 50):
print n
	except Exception, e:
		running = False
		print 'Exception raised:', e
	print 'Biggest number of threads:', n

if __name__ == '__main__':
	test()
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Determine an object is a subclass of another

2007-01-09 Thread Felipe Almeida Lessa
On 9 Jan 2007 07:01:31 -0800, abcd [EMAIL PROTECTED] wrote:
 anyways, is there a way to check without having an instance of the
 class?

In [1]: class A:
   ...: pass
   ...:

In [2]: class B(A):
   ...: pass
   ...:

In [3]: issubclass(B, A)
Out[3]: True

In [4]: isinstance(B(), B)
Out[4]: True

In [5]: isinstance(B(), A)
Out[5]: True

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


Re: Suitability for long-running text processing?

2007-01-08 Thread Felipe Almeida Lessa
On 1/8/07, tsuraan [EMAIL PROTECTED] wrote:
[snip]
 The loop is deep enough that I always interrupt it once python's size is
 around 250 MB.  Once the gc.collect() call is finished, python's size has
 not changed a bit.
[snip]
 This has been tried under python 2.4.3 in gentoo linux and python 2.3 under
 OS X.3.  Any suggestions/work arounds would be much appreciated.

I just tried on my system

(Python is using 2.9 MiB)
 a = ['a' * (1  20) for i in xrange(300)]
(Python is using 304.1 MiB)
 del a
(Python is using 2.9 MiB -- as before)

And I didn't even need to tell the garbage collector to do its job. Some info:

$ cat /etc/issue
Ubuntu 6.10 \n \l

$ uname -r
2.6.19-ck2

$ python -V
Python 2.4.4c1

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


Re: Suitability for long-running text processing?

2007-01-08 Thread Felipe Almeida Lessa
On 1/8/07, tsuraan [EMAIL PROTECTED] wrote:


  I just tried on my system
 
  (Python is using 2.9 MiB)
   a = ['a' * (1  20) for i in xrange(300)]
  (Python is using 304.1 MiB)
   del a
  (Python is using 2.9 MiB -- as before)
 
  And I didn't even need to tell the garbage collector to do its job. Some
 info:

 It looks like the big difference between our two programs is that you have
 one huge string repeated 300 times, whereas I have thousands of
 four-character strings.  Are small strings ever collected by python?

In my test there are 300 strings of 1 MiB, not a huge string repeated. However:

$ python
Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02)
[GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2
Type help, copyright, credits or license for more information.
 # Python is using 2.7 MiB
... a = ['1234' for i in xrange(10  20)]
 # Python is using 42.9 MiB
... del a
 # Python is using 2.9 MiB

With 10,485,760 strings of 4 chars, it still works as expected.

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


Re: Why less emphasis on private data?

2007-01-07 Thread Felipe Almeida Lessa
On 07 Jan 2007 02:01:44 -0800, Paul Rubin
http://phr.cx@nospam.invalid wrote:
 Dennis Lee Bieber [EMAIL PROTECTED] writes:
__ (two leading underscores) results in name-mangling. This /may/ be
  used to specify private data, but is really more useful when one is
  designing with multiple super classes:

 Trouble with this is you can have two classes with the same name,
 perhaps because they were defined in different modules, and then the
 name mangling fails to tell them apart.

What is the chance of having to inherit from two classes from
different modules but with exactly the same name *and* the same
instance variable name?

Of course you're being very pessimistic or extremely unlucky.

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


Re: how to find the longst element list of lists

2007-01-07 Thread Felipe Almeida Lessa
On 1/7/07, Michael M. [EMAIL PROTECTED] wrote:
 How to find the longst element list of lists?

s1 = [q, e, d]
s2 = [a, b]
s3 = [a, b, c, d]

s = [s1, s2, s3]
s.sort(key=len, reverse=True)
print s[0] is s3
print s[1] is s1
print s[2] is s2

sx1, sx2, sx3 = s
print 'sx1:', sx1
print 'sx2:', sx2
print 'sx3:', sx3

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


Re: Packaging up a Python/Twisted Matrix application...

2007-01-04 Thread Felipe Almeida Lessa
On 1/4/07, Chaz Ginger [EMAIL PROTECTED] wrote:
 I have a rather large Python/Twisted Matrix application that will be run
 on Windows, Linux and perhaps Macs. I was wondering if there are any
 tools that can be used to create an installer that will bring in Python,
 Twisted Matrix, my application libraries and anything else I need?

I haven't tried with Twisted, but I had success in using py2exe + Inno
Setup on a program dependent on Python + ReportLab + pygtk. As both
ReportLab and pygtk got even C extensions, I don't see why this setup
wouldn't work with Twisted.

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


Re: A python library to convert RTF into PDF ?

2007-01-03 Thread Felipe Almeida Lessa
On 3 Jan 2007 10:52:02 -0800, [EMAIL PROTECTED]
[EMAIL PROTECTED] wrote:
 I have tried to
 convert them to tex using OpenOffice, but the result is ugly as hell.

Why not use OO.org to convert DOC to PDF? It does so natively, IIRC.

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


Re: static object

2007-01-03 Thread Felipe Almeida Lessa
On 1/3/07, meelab [EMAIL PROTECTED] wrote:
 I am looking for a way to create a static object or a static class -
 terms might be inappropriate - having for instance:

An example will speak better than me:

class Card(object):
__cards = {}

def __init__(self, number, suit):
self.number, self.suit = number, suit

def __new__(cls, number, suit):
try:
return cls.__cards[(number, suit)]
except KeyError:
obj = object.__new__(cls, number, suit)
cls.__cartas[(number, suit)] = obj
return obj


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


Re: Are all classes new-style classes in 2.4+?

2006-12-31 Thread Felipe Almeida Lessa
On 31 Dec 2006 03:57:04 -0800, Isaac Rodriguez
[EMAIL PROTECTED] wrote:
 I am using Python 2.4, and I was wondering if by default, all
 classes are assumed to be derived from object.

This won't tell you advantages or disadvantages, but will show you
that the default still is the old-style:

 class old:
... pass
...
 type(old())
type 'instance'
 dir(old())
['__doc__', '__module__']

 class new(object):
... pass
...
 type(new())
class '__main__.new'
 dir(new())
['__class__', '__delattr__', '__dict__', '__doc__',
'__getattribute__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__',
'__weakref__']


In general, even if you don't understand the differences, it's better
to use new-style (they're new ;-). Anyway, see
http://effbot.org/pyref/new-style-and-classic-classes.htm for a little
more information.

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


Re: A question about unicode() function

2006-12-31 Thread Felipe Almeida Lessa
On 31 Dec 2006 05:20:10 -0800, JTree [EMAIL PROTECTED] wrote:
 def funUrlFetch(url):
 lambda url:urllib.urlopen(url).read()

This function only creates a lambda function (that is not used or
assigned anywhere), nothing more, nothing less. Thus, it returns None
(sort of void) no matter what is its argument. Probably you meant
something like

def funUrlFetch(url):
return urllib.urlopen(url).read()

or

funUrlFetch = lambda url:urllib.urlopen(url).read()


 objUrl = raw_input('Enter the Url:')
 content = funUrlFetch(objUrl)

content gets assigned None. Try putting print content before the unicode line.

 content = unicode(content,gbk)

This, equivalent to unicode(None, gbk), leads to

 TypeError: coercing to Unicode: need string or buffer, NoneType found

None's are not strings nor buffers, so unicode() complains.

See ya,

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


Re: BeautifulSoup vs. loose chars

2006-12-26 Thread Felipe Almeida Lessa
On 26 Dec 2006 04:22:38 -0800, placid [EMAIL PROTECTED] wrote:
 So do you want to remove  or replace them with amp; ? If you want
 to replace it try the following;

I think he wants to replace them, but just the invalid ones. I.e.,

This  this amp; that

would become

This amp; this amp; that


No, i don't know how to do this efficiently. =/...
I think some kind of regex could do it.

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


Re: Async callback in python

2006-12-04 Thread Felipe Almeida Lessa
On 4 Dec 2006 20:18:22 -0800, Linan [EMAIL PROTECTED] wrote:
 3, If not, where to get the real one(s)?

After reading Calvin's mail, you may want to see
http://twistedmatrix.com/ . It's an assynchronous library built around
the concept of deferreds (think of callbacks). You may like it =).

Cya,

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


Re: global name 'self' is not defined

2006-12-02 Thread Felipe Almeida Lessa
On 2 Dec 2006 10:42:28 -0800, Evan [EMAIL PROTECTED] wrote:
 Why is it that the first call works fine, but the second tells me
 'global name 'self' is not defined'?  What I want is to have the
 dictionary 'estoc' available in my calling script.

Well, you have not posted the code that is causing the problem,
nowhere in your mail there's a reference to self.


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


Re: What are python closures realy like?

2006-12-01 Thread Felipe Almeida Lessa
On 12/1/06, Karl Kofnarson [EMAIL PROTECTED] wrote:
[snip]
 def fun_basket(f):
 common_var = [0]
 def f1():
 print common_var[0]
 common_var[0]=1
 def f2():
 print common_var[0]
 common_var[0]=2
 if f == 1:
 return f1
 if f == 2:
 return f2

Everytime you call fun_basket you create another common_var.

 However, calling f1=fun_basket(1); f2 = fun_basket(2) and
 then f1(); f2() returns 0 and 0.

Two calls to fun_basket, two different common_var's, two f1's and two
f2's. Each f1/f2 pair have access to a different common_var, so it's
working as expected. To work as you expected, fun_basket should be on
the same block common_var is defined.

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


Re: Event driven server that wastes CPU when threaded doesn't

2006-10-29 Thread Felipe Almeida Lessa
29 Oct 2006 14:18:02 -0800, Paul Rubin http://phr.cx@nospam.invalid:
 Nick Vatamaniuc [EMAIL PROTECTED] writes:
  The simplest solution is to change your system and put the DB on the
  same machine thus greatly reducing the time it takes for each DB query
  to complete (avoid the TCP stack completely).

 Since when do any db's let you avoid the TCP stack, even on the same
 machine?

Since there are Unix sockets? A quick google:

http://dev.mysql.com/doc/refman/5.0/en/multiple-unix-servers.html
http://archives.postgresql.org/pgsql-hackers/1997-10/msg00568.php


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


Re: How to print a file in binary mode

2006-10-22 Thread Felipe Almeida Lessa
22 Oct 2006 06:33:50 -0700, Lucas [EMAIL PROTECTED]:
I known how to do it.read() return a string. so1) bytes = read(1) #read the file by bit.2) chrString= ord(bytes) #convert the string to ASCII.3) print numberToBinary(chrString) #convert the ASCII to Binary using
my function.4) Loop[numberToBinary(ord(x)) for x in f.read()] ?-- Felipe.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: PATCH: Speed up direct string concatenation by 20+%!

2006-09-29 Thread Felipe Almeida Lessa
28 Sep 2006 19:07:23 -0700, Larry Hastings [EMAIL PROTECTED]:
 THE BENCHMARKS

 Benchmark 1:
 def add(a, b, c, ... t): return a + b + c + ... + t
 for i in range(1000): add(aaa, bbb, ccc, ..., ttt)
[snip]

What about a + b? Or a + b + c? Does it have a large overhead on
small string concatenations?

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


Re: QOTW (was Re: does anybody earn a living programming in python?)

2006-09-26 Thread Felipe Almeida Lessa
2006/9/26, Sybren Stuvel [EMAIL PROTECTED]:
 Aahz enlightened us with:
  Fredrik Lundh  [EMAIL PROTECTED] wrote:
 
 well, if you're only watching mtv, it's easy to think that there's
 obviously not much demand for country singers, blues musicians,
 British hard rock bands, or melodic death metal acts.
 
  Any other votes for this being QOTW?

 +1 here


+1 here, too

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


Re: does anybody earn a living programming in python?

2006-09-25 Thread Felipe Almeida Lessa
2006/9/25, Robert Kern [EMAIL PROTECTED]:
 walterbyrd wrote:
  If so, I doubt there are many.
 
  I wonder why that is?

 Well I do. So do the other dozen or so developers at my company. We're looking
 to hire a few more, in fact.

And there are also those ReportLab guys:

www.reportlab.com

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


Re: What is the best way to get a web page?

2006-09-24 Thread Felipe Almeida Lessa
24 Sep 2006 10:09:16 -0700, Rainy [EMAIL PROTECTED]:
 Functionally they are the same, but third line included in Firefox.
 Opera View Source command produces the same result as Python.
[snip]

It's better to compare with the result of a downloader-only (instead
of a parser), like wget on Unix. That way you'll get exactly the same
bytes (assuming the page is static).

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


Re: Decorator cllass hides docstring from doctest?

2006-09-21 Thread Felipe Almeida Lessa
2006/9/21, Berthold Höllmann [EMAIL PROTECTED]:
 Saving the following code to a file and running the code through
 python does not give the expected error. disableling the @decor line
 leads to the expected error message. Is this a bug or an overseen
 feature?

Try the new_decor class described below:

 class decor(object):
... def __init__(self, f):
... self.f = f
... def __call__(self, *args, **kw):
... return self.f(*args, **kw)
...
 class new_decor(object):
... def __init__(self, f):
... self.f = f
... self.__doc__ = f.__doc__
... self.__name__ = f.__name__
... def __call__(self, *args, **kw):
... return self.f(*args, **kw)
...
 def f(a, b):
... '''
...  f(1, 2)
... False
...  f(2, 2)
... False
... '''
... return a == b
...
 f.__doc__
'\n\t f(1, 2)\n\tFalse\n\t f(2, 2)\n\tFalse\n\t'
 decor(f).__doc__ == f.__doc__
False
 new_decor(f).__doc__ == f.__doc__
True


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

Re: How to stop an [Rpyc] server thread?

2006-09-11 Thread Felipe Almeida Lessa
7 Sep 2006 23:38:08 -0700, Tal Einat [EMAIL PROTECTED]:
  I'm not an expert in socket programming, but I can't see the
  correlation between the listener socket being in timeout mode and a
  different behavior the other sockets..
  Anyhow the main goal is being able to shut down the thread of the rpyc
  server, any other way is an appreciated suggestion.

 Now to the real issue. I've also had such weird problems with socket
 timeout in Python. The best workaround I found is to use select() to
 check for activity on the socket(s), and use select()'s timeout
 mechanism. So far, this has worked without a hitch on both WindowsXP
 and Solaris Sparc9 installations.

Twisted[1] is the answer. I've never seen a better framework for using
sockets, it's painless.  I created two versions of the same protocol
(both client and server), one using sockets + select, another using
Twisted. The sockets version had 2x lines than the Twisted one and
lots of bugs. Sockets may fail *anywhere* in your code, and Twisted
takes care of all details for you[2]. Simply Sweet.

Cheers,

[1] http://www.twistedmatrix.com/
[2] Of couse this is just *one* advantage of the Twisted framework...

PS.: No, I wasn't paid for this e-mail ;-)

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


Re: No ValueError for large exponents?

2006-09-10 Thread Felipe Almeida Lessa
2006/9/6, Robin Becker [EMAIL PROTECTED]:
 enigmadude wrote:
  As many have heard, IronPython 1.0 was released. When I was looking
  through the listed differences between CPython and IronPython, the
  document mentioned that using large exponents such as 10 **
  735293857239475 will cause CPython to hang, whereas IronPython will
  raise a ValueError. Trying this on my own machine, it did indeed seem
  to cause CPython to hang. In cases such as this, should this be
  considered a bug in the CPython implementation that needs to be fixed?
  Or is there a reason for this, such as consideration of future changes
  and language definition vs language implementation, etc.?
 
 I suspect the hang may be python actually trying to work out the
 1 followed by 735293857239475 zeroes. Perhaps IronPython has a forward
 looking algorithm that knows when to give up early.

I think that IronPython does the same as the .Net runtime does. Look
at boo's output:

$ booish
Welcome to booish, an interpreter for the boo programming language.

Running boo 0.7.5.2013.

The following builtin functions are available:
dir(Type): lists the members of a type
help(Type): prints detailed information about a type
load(string): evals an external boo file
globals(): returns the names of all variables known to the interpreter

Enter boo code in the prompt below.
 10**100
1E+100
 10**100
∞
 10**735293857239475
ERROR: Error reading from 'input3': 'Value too large or too small.'.
 (10**100).GetType()
System.Double

Well, it's a double on boo instead of a very long int as in Python. I
don't know if in IronPython it's the same.

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

Re: ANN: Pocoo (bulletin board software) 0.1 beta released

2006-09-10 Thread Felipe Almeida Lessa
10 Sep 2006 16:17:08 -0700, Paul Rubin http://phr.cx@nospam.invalid:
 So, I think it's not worth thinking about writing yet another BBS
 unless it can handle a Slashdot-sized load on a commodity PC.

Python is slow. Psyco helps, but you should use C instead.

And yes, I am kidding =)

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


Re: Best Middle Tier Architechure?

2006-09-08 Thread Felipe Almeida Lessa
2006/9/7, Butternut Squash [EMAIL PROTECTED]:
 right now we are using c# and .net remoting in a way that just is not
 efficient.

 I want to rewrite a lot of what we do in python. I have seen XML-RPC and
 soap.  Are there other options?

It surely depends on what's going to be on the other sides. If
everything is Python, you may use Twisted.Spread. If you have to
communicate with different languages and plataforms, maybe CORBA
helps. Well, I'm sure a lot of people know more options than I do
here.

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


Re: best split tokens?

2006-09-08 Thread Felipe Almeida Lessa
8 Sep 2006 13:41:48 -0700, Jay [EMAIL PROTECTED]:
 Let's say, for instance, that one was programming a spell checker or
 some other function where the contents of a string from a text-editor's
 text box needed to be split so that the resulting array has each word
 as an element.  Is there a shortcut to do this and, if not, what's the
 best and most efficient token group for the split function to achieve
 this?

your_string.split()

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


Re: Best Middle Tier Architechure?

2006-09-08 Thread Felipe Almeida Lessa
2006/9/8, Butternut Squash [EMAIL PROTECTED]:
 I have to support multiple applications using different schema and
 databases.  Would like to present as much as a unified interface as
 possible.

I'd recomend CORBA as it supports multiple platforms and languages.
SOAP and XML-RPC can be used as well, but I'm afraid performance can
be a problem if a lot of calls are made or big/complex objects are
transfered.

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


Re: convert loop to list comprehension

2006-09-08 Thread Felipe Almeida Lessa
8 Sep 2006 17:37:02 -0700, [EMAIL PROTECTED] [EMAIL PROTECTED]:
 1. Using an _ is an interesting way to use a throw-away variable. Never
 would I think of that ... but, then, I don't do Perl either :)

It's a kind of convention. For example, Pylint complains for all
variables you set and don't use unless its name is _.

 2. Any reason for xrange() instead of range()

It's faster.

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


Re: convert loop to list comprehension

2006-09-08 Thread Felipe Almeida Lessa
08 Sep 2006 17:33:20 -0700, Paul Rubin http://phr.cx@nospam.invalid:
 [EMAIL PROTECTED] writes:
  print sum( ([i]*n for i,n in enumerate(seq)), [])

 Wow, I had no idea you could do that.  After all the discussion about
 summing strings, I'm astonished.

Why? You already had the answer: summing *strings*. Everything but
strings can be summed by sum(). E.g.:

Python 2.4.3 (#2, Apr 27 2006, 14:43:58)
[GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2
Type help, copyright, credits or license for more information.
 class x(object):
... def __add__(self, other):
... return x(self.a + other.a)
... def __init__(self, a):
... self.a = a
...
 t = x(10)
 t.a
10
 sum([t, t])
Traceback (most recent call last):
  File stdin, line 1, in ?
TypeError: unsupported operand type(s) for +: 'int' and 'x'
 sum([t, t], t)
__main__.x object at 0xb7d6752c
 _.a
30
 sum([t, t], x(0)).a
20
 sum([t, t]*1000, t).a
20010


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


Re: python vs java

2006-09-07 Thread Felipe Almeida Lessa
2006/9/7, Bruno Desthuilliers [EMAIL PROTECTED]:
 I don't think one could pretend writing a cross-platform application
 without testing it on all targeted platforms.

E.g: while creating a free software, you may not have an Apple
computer but you may want to be *possible* to run your program there.
You don't test it, but you *think* it runs there. Not everybody has a
spare MacOS X to test apps.

Of course, if your software *needs* to run in some particular OS then
you have to test on it.

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


Re: [ANN] IronPython 1.0 released today!

2006-09-07 Thread Felipe Almeida Lessa
2006/9/5, Jim Hugunin [EMAIL PROTECTED]:
 I'm extremely happy to announce that we have released IronPython 1.0 today!
  http://www.codeplex.com/IronPython

Does IronPython runs Twisted?

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


Re: IronPython 1.0 released today!

2006-09-07 Thread Felipe Almeida Lessa
7 Sep 2006 16:34:56 -0700, Luis M. González [EMAIL PROTECTED]:
 People are already porting some of these libraries.
 Those that are written in pure python don't need to be ported, but
 those that rely on c extensions can be rewritten in c# or any other
 .NET language.

Or in C that is P/Invoked from the CLR, although this option is
somewhat less portable. See
http://www.mono-project.com/Interop_with_Native_Libraries

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

Re: threading support in python

2006-09-05 Thread Felipe Almeida Lessa
4 Sep 2006 19:19:24 -0700, Sandra-24 [EMAIL PROTECTED]:
 If there was a mod_dotnet I wouldn't be using
 CPython anymore.

I guess you won't be using then: http://www.mono-project.com/Mod_mono

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


Re: Higher-level OpenGL modules

2006-09-05 Thread Felipe Almeida Lessa
5 Sep 2006 03:44:47 -0700, Leon [EMAIL PROTECTED]:
 Greetings,

 Does anybody know of or is working on any python modules that allow for
 a direct but higher-level interface to OpenGL? For example, quick
 functions to draw lines, curves, and basic shapes; define hsb color
 mode; fill and stroke operations; easy loading of images, svg files,
 etc (much like the processing language -
 http://www.processing.org/reference/index.html).  The closest thing I
 could find was devachan - http://www.cesaremarilungo.com/sw/devachan/,
 but its very limited. Any response would be greatly appreciated.

Soya? I don't know if it fulfill your needs, though.
http://home.gna.org/oomadness/en/soya/


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


Re: Client-side TCP socket receiving Address already in use upon connect

2006-09-03 Thread Felipe Almeida Lessa
2006/9/3, Alex Martelli [EMAIL PROTECTED]:
 Reflecting on the OP's use case, since all connections are forever being
 made to the same 16 servers, why not tweak thinks a bit to hold those
 connections open for longer periods of time, using a connection for many
 send/receive transactions instead of opening and closing such
 connections all of the time?  That might well work better...

Connecting to 16 differente servers per second gives a very poor
performance, right? There's some overhead in creating TCP connections,
even on fast networks and computers. Am I right?

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


Re: What do you want in a new web framework?

2006-08-30 Thread Felipe Almeida Lessa
2006/8/30, Ben Finney [EMAIL PROTECTED]:
 re
 struct
 unicodedata
 decimal
 random
 logging
 Queue
 urlparse
 email

operator
cStringIO
math
cmath
sets (merged to the language)
itertools
os + stat
time
tempfile
glob

Not that I use them all the time, but they are really useful and
usually fulfill my needs.

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


Re: GC and security

2006-08-30 Thread Felipe Almeida Lessa
2006/8/30, Les Schaffer [EMAIL PROTECTED]:
 is there a best practice way to do this?

I'm not a cryptographer, but you should really try the function
collect() inside the gc module.

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


Re: range of int() type.

2006-08-23 Thread Felipe Almeida Lessa
23 Aug 2006 17:28:48 -0700, KraftDiner [EMAIL PROTECTED]:
 This is obvious... but how do I crop off the high order bits if
 necessary?
 a[0]0x ?

min(a[0], 0x) ?

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


Re: List comparison help please

2006-08-20 Thread Felipe Almeida Lessa
20 Aug 2006 14:47:14 -0700, Bucco [EMAIL PROTECTED]:
 I am trying to compare a list of items to the list of files generated
 by os.listdir.  I am having trouble getting this to work and think I
 may be going down the wrong path.  Please let me know if hter is a
 better way to do this.  THis is what I have for my class so far:


Have you tried using sets?

 import os
 os.listdir('/')
['lost+found', 'var', 'etc', 'media', 'cdrom', 'bin', 'boot', 'dev',
'home', 'initrd', 'lib', 'mnt', 'opt', 'proc', 'root', 'sbin', 'srv',
'sys', 'tmp', 'usr', 'initrd.img', 'vmlinuz', 'windows',
'initrd.img.old', 'vmlinuz.old']
 s = set(os.listdir('/'))
 p = set(['opt', 'mnt', 'initrd', 'home', 'tmp', 'lib', 'media',
'boot', 'usr', 'var', 'proc', 'bin', 'sys', 'initrd.img.old', 'cdrom',
'lost+found', 'sbin', 'vmlinuz.old', 'windows'])
 s - p
set(['dev', 'etc', 'vmlinuz', 'srv', 'root', 'initrd.img'])



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


Re: Convert string to mathematical function

2006-08-01 Thread Felipe Almeida Lessa
Em Ter, 2006-08-01 às 18:45 -0700, jeremito escreveu:
 I am extending python with C++ and need some help.  I would like to
 convert a string to a mathematical function and then make this a C++
 function.  

I may be wrong, but I don't think you can create new C++ functions
on-the-fly. At least I had the impression that only VMs could do it
(e.g. System.Reflection on .NET/Mono world and, of course, Python). 

 My one idea (although I don't
 know how to implement it, I'm still new at this) is to pass to C++ a
 pointer to a (Python) function.  Will this work?

I think it will, but I can't tell you how =).

-- 
Felipe.

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

Re: math.pow(x,y)

2006-06-11 Thread Felipe Almeida Lessa
Em Dom, 2006-06-11 às 11:19 -0700, fl1p-fl0p escreveu:
 import math
 math.pow(34564323, 456356)
 
 will give math range error.
 
 how can i force python to process huge integers without math range
 error? Any modules i can use possibly?

34564323**456356 ?

-- 
Felipe.

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

Re: how to get the length of a number

2006-06-11 Thread Felipe Almeida Lessa
Em Dom, 2006-06-11 às 20:10 +, Stan Cook escreveu:
 Can anyone tell me how to get the length of a number.  I 
 know len(string) will get the length of a string, but it 
 doesn't like len(int).  I seem to remember something like %s 
 string.  I tried to set a variable = to %s int, but that 
 doesn't work.  Is there a function I've forgotten about to 
 convert an integer to a string?

To convert an integer i to a string:

str(i)   or   %s % i


To see how many decimal digits it has:

import math
math.ceil(math.log(i, 10))

-- 
Felipe.

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

Re: how to get the length of a number

2006-06-11 Thread Felipe Almeida Lessa
Em Dom, 2006-06-11 às 13:17 -0700, Saketh escreveu:
 Stan Cook wrote:
  Can anyone tell me how to get the length of a number.  I
  know len(string) will get the length of a string, but it
  doesn't like len(int).  I seem to remember something like %s
  string.  I tried to set a variable = to %s int, but that
  doesn't work.  Is there a function I've forgotten about to
  convert an integer to a string?
 
  Regards
 
  Stan
 
 Use str(int). Then use len(). For example, len(str(12345)) will give
 you 5.

$ python2.4 -mtimeit -s 'x=12345' 'len(str(x))' 100 loops, best of
3: 1.33 usec per loop
$ python2.4 -mtimeit -s 'x=12345;from math import ceil,log' 'ceil(log(x,
10))'
100 loops, best of 3: 1.54 usec per loop
$ python2.4 -mtimeit -s 'x=12345**123' 'len(str(x))' 1000 loops, best of
3: 209 usec per loop
$ python2.4 -mtimeit -s 'x=12345**123;from math import ceil,log'
'ceil(log(x, 10))'
100 loops, best of 3: 1.55 usec per loop
$ python2.4 -mtimeit -s 'x=12345**1234' 'len(str(x))' 100 loops, best of
3: 19.2 msec per loop
$ python2.4 -mtimeit -s 'x=12345**1234;from math import ceil,log'
'ceil(log(x, 10))'
100 loops, best of 3: 1.53 usec per loop


-- 
Felipe.

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

Re: how to get the length of a number

2006-06-11 Thread Felipe Almeida Lessa
Em Dom, 2006-06-11 às 22:33 +0200, Sybren Stuvel escreveu:
 Felipe Almeida Lessa enlightened us with:
  To see how many decimal digits it has:
 
  import math
  math.ceil(math.log(i, 10))
 
 That doesn't work properly.
 
  import math
  math.ceil(math.log(1, 10))
 4.0
  math.ceil(math.log(10001, 10))
 5.0
 
 But 1 certainly has as much digits as 10001.

Hmmm, you're right.

math.floor(math.log(x, 10)) + 1

-- 
Felipe.

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

Re: Writing PNG with pure Python

2006-06-09 Thread Felipe Almeida Lessa
Em Sex, 2006-06-09 às 12:30 -0400, Alan Isaac escreveu:
 It's your code, so you get to license it.
 But if you wish to solicit patches,
 a more Pythonic license is IMHO more likely
 to prove fruitful.

Pythonic license? That's new to me. I can figure out what a
Python-like license is, but I'm clueless about a Pythonic license.

-- 
Felipe.

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

Re: Killing a thread

2006-06-09 Thread Felipe Almeida Lessa
Em Sex, 2006-06-09 às 13:54 -0700, Manish Marathe escreveu:
 On 6/9/06, Fredrik Lundh [EMAIL PROTECTED] wrote:
 Manish Marathe wrote:
 
  I am creating threads using my self defined class which
 inherits the
  threading.Thread class. I want to know how can I kill the
 threads which
  are being created by the object of my self defined class. 
 
 you cannot kill a thread from the outside; you have to
 design your
 thread tasks so they can kill themselves, when asked to do
 that.
 
 Thanks for the reply. So can a thread listen to an event i.e. can we
 send an event to the thread indicating to kill itself.

A plain simple boolean flag will certainly do the job. For example

def run(self):
self.running = True
while self.running:
blah()

def stop(self):
self.running = False


-- 
Felipe.

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

Re: 10GB XML Blows out Memory, Suggestions?

2006-06-06 Thread Felipe Almeida Lessa
Em Ter, 2006-06-06 às 13:56 +, Paul McGuire escreveu:
 (just can't open it up like a text file)

Who'll open a 10 GiB file anyway?

-- 
Felipe.

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

Re: Open Source Charting Tool

2006-06-02 Thread Felipe Almeida Lessa
Em Sex, 2006-06-02 às 15:42 -0500, Larry Bates escreveu:
 ReportLab Graphics can do 2D and pie charts, but I don't think it does
 3D charts yet.
 
 www.reporlab.org

It does, but I'm not sure if the PNG backend is as good as the PDF one.

-- 
Felipe.

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

Re: Open Source Charting Tool

2006-06-02 Thread Felipe Almeida Lessa
Em Sex, 2006-06-02 às 16:56 -0400, A.M escreveu:
 I can't browse to www.reporlab.org, but I found http://www.reportlab.com/ 
 which has a  commercial charting product. Is that what you referring to?

ReportLab (the commercial bussiness thing on .com) is where the main
developers of ReportLab (a library freely available on www.reporlab.org)
work.  So what you want really is .org, but apparently it's having
problems right now. 

-- 
Felipe.

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

Re: PEP-xxx: Unification of for statement and list-comp syntax

2006-05-21 Thread Felipe Almeida Lessa
Em Dom, 2006-05-21 às 17:11 +0200, Heiko Wundram escreveu:
   for node in tree if node.haschildren():
   do something with node
 
 as syntactic sugar for:
 
   for node in tree:
   if not node.haschildren():
   continue
   do something with node 

Today you can archive the same effect (but not necessarily with the same
performance) with:

for node in (x for x in tree if x.haschildren()):
do something with node

But that's ugly...

-- 
Felipe.

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

Re: PEP-xxx: Unification of for statement and list-comp syntax

2006-05-21 Thread Felipe Almeida Lessa
Em Dom, 2006-05-21 às 11:52 -0700, gangesmaster escreveu:
  Today you can archive the same effect (but not necessarily with the same
  performance) with:
 
  for node in (x for x in tree if x.haschildren()):
  do something with node
 
 true, but it has different semantic meanings
 

I know, that's also why I don't oppose the PEP.

-- 
Felipe.

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

Re: calling upper() on a string, not working?

2006-05-16 Thread Felipe Almeida Lessa
Em Ter, 2006-05-16 às 20:25 +, John Salerno escreveu:
 it doesn't seem to work. The full code is below if it helps to understand.

Why doesn't it work? What does it do, what did you expect it to do?

 ''.join(set('hi'))
'ih'
 ''.join(set('HI'))
'IH'
 ''.join(set('hiHI'))
'ihIH'
 ''.join(set('hiHI'.upper()))
'IH'


-- 
Felipe.

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

Re: New tail recursion decorator

2006-05-10 Thread Felipe Almeida Lessa
Em Ter, 2006-05-09 às 23:30 -0700, Kay Schluehr escreveu:
 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691

Is it thread safe?

-- 
Felipe.

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

Re: NaN handling

2006-05-06 Thread Felipe Almeida Lessa
Em Sex, 2006-05-05 às 16:37 -0400, Ivan Vinogradov escreveu:
 This works to catch NaN on OSX and Linux:
 
 # assuming x is a number
 if x+1==x or x!=x:
   #x is NaN

This works everywhere:

nan = float('nan')

.
.
.

if x == nan:
# x is not a number

-- 
Felipe.

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

Re: problems when unpacking tuple ...

2006-04-22 Thread Felipe Almeida Lessa
Em Sáb, 2006-04-22 às 09:21 -0700, harold escreveu:
 for line in sys.stdin :
 try :
 for a,b,c,d in line.split() :
 pass
 
 except ValueError , err :
 print line.split()
 raise err 

Try this:

for a, b, c, d in sys.stdin:
 print a, b, c, d

-- 
Felipe.

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

Re: problems when unpacking tuple ...

2006-04-22 Thread Felipe Almeida Lessa
Em Sáb, 2006-04-22 às 14:25 -0300, Felipe Almeida Lessa escreveu:
 Em Sáb, 2006-04-22 às 09:21 -0700, harold escreveu:
  for line in sys.stdin :
  try :
  for a,b,c,d in line.split() :
  pass
  
  except ValueError , err :
  print line.split()
  raise err 
 
 Try this:
 
 for a, b, c, d in sys.stdin:
  print a, b, c, d
 

Forget that. It was stupid. You should try this instead:

for line in sys.stdin:
a, b, c, d = line.split()

-- 
Felipe.

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

Re: Problem calling math.cos()

2006-04-22 Thread Felipe Almeida Lessa
Em Sáb, 2006-04-22 às 15:14 -0400, Sambo escreveu:
 when I import it (electronics) in python.exe in windows2000 and 
 try to use it, it croaks.  ??? 

$ python2.4
Python 2.4.3 (#2, Mar 30 2006, 21:52:26)
[GCC 4.0.3 (Debian 4.0.3-1)] on linux2
Type help, copyright, credits or license for more information.
 import math
 def ac_add_a_ph( amp1, ph1, amp2, ph2 ):
... amp3 = 0.0
... ph3 = 0.0
... ac1 = ( 0, 0j )
... ac2 = ( 0, 0j )
... ac3 = ( 0, 0j )
... ac1 = complex( amp1 * math.cos( math.radians( ph1 ) ), amp1 *
math.sin( math.radians( ph1 ) ) )
... ac2 = complex( amp2 * math.cos( math.radians( ph2 ) ), amp2 *
math.sin( math.radians( ph2 ) ) )
... ac3 = ac1 + ac2
... amp3 = math.abs( ac3 )
... ph3 = math.atan( ac3.imag / ac3.real )
... return [amp3, ph3]
...
 ac_add_a_ph(10, 0, 6, 45)
Traceback (most recent call last):
  File stdin, line 1, in ?
  File stdin, line 10, in ac_add_a_ph
AttributeError: 'module' object has no attribute 'abs'
 abs
built-in function abs
 def ac_add_a_ph(amp1, ph1, amp2, ph2):
... ac1 = complex(amp1 * math.cos(math.radians(ph1)), amp1 *
math.sin(math.radians(ph1)))
... ac2 = complex(amp2 * math.cos(math.radians(ph2)), amp2 *
math.sin(math.radians(ph2)))
... ac3 = ac1 + ac2
... ph3 = math.atan(ac3.imag / ac3.real)
... return [abs(amp3), ph3]
...
 ac_add_a_ph(10, 0, 6, 45)
[14.86111751324192, 0.28951347254362308]




So:
---
import math

def polar(rho, theta, theta_in_radians=False)
Creates a complex number from its polar form.
# Avoid repeating yourself by creating different functions
if not theta_in_radians:
theta = math.radians(theta)
return complex(rho * math.cos(theta), rho * math.sin(theta))

def ac_add_a_ph(amp1, ph1, amp2, ph2):
Add two complexes together from their polar form.
# You don't have to initialize the variables with 0.0 and such.
ac3 = polar(amp1, ph1) + polar(amp2, ph2)
ph3 = math.atan(ac3.imag / ac3.real)
return (abs(ac3), ph3) # Use a tuple in this case
--



*But*, I encourage you using the complex numbers themselves instead of
converting to and from over and over.


HTH,

-- 
Felipe.

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

Re: Performance of Python 2.3 and 2.4

2006-04-22 Thread Felipe Almeida Lessa
Em Dom, 2006-04-23 às 00:20 +0200, Michal Kwiatkowski escreveu:
 Hi!
 
 I was just wondering...

Probably there is another factor involved:

$ python2.3
Python 2.3.5 (#2, Mar  6 2006, 10:12:24)
[GCC 4.0.3 20060304 (prerelease) (Debian 4.0.2-10)] on linux2
Type help, copyright, credits or license for more information.
 import timeit
 timeit.Timer('2**1').timeit(1)
4.6463479995727539
 timeit.Timer('112233445566778899 * 112233445566778899').timeit()
0.44853687286376953


$ python2.4
Python 2.4.3 (#2, Mar 30 2006, 21:52:26)
[GCC 4.0.3 (Debian 4.0.3-1)] on linux2
Type help, copyright, credits or license for more information.
 import timeit
 timeit.Timer('2**1').timeit(1)
4.9987671375274658
 timeit.Timer('112233445566778899 * 112233445566778899').timeit()
0.36968302726745605

-- 
Felipe.

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

Re: PyLint results?

2006-04-21 Thread Felipe Almeida Lessa
Em Sex, 2006-04-21 às 13:49 -0400, Michael Yanowitz escreveu:
I ran the new pylint and my code and I had a few questions on why those
 are warnings or what I can do to fix them:

You can ignore the warnings you don't like with the --disable-msg
option. Also, you can add a header to the file to apply a rule just to
it.

 1) W:  0: Too many lines in module (1587)
  Why is 1587 considered too many lines? Would there be necessarily be an
advantage to split it up into 2 or 3 files? Can I up the limit?

Because Python is terse, and this can be a really large module. Or not.
PyLint is not perfect, maybe you should disable this warning.

 2) C:  0: Missing required attribute __revision__
What is this? Is that for CVS? I don't use CVS (we use SVN). I have not
seen any sample code which includes this tag yet. But if I include
__revision 1.0  somewhere in the code it will remove that warning?

Don't include the variable just to remove the warning -- disable it.

 3) W:230:readDiscreteData: Using the global statement
What is wrong with using the global statement? 

Your code can get unmaintainable if you abuse of it. If you really need
it and know how to use it well, disable the warning. 

 4) W:261:getDiscreteData: Catch Exception
What is wrong with that?

You may catch things you don't want to catch, like KeyboardInterrupt
exceptions.

 5) R:547:readDiscreteData: Too many branches (28/12)
Python doesn't have the switch/case statements that C/C++ have. So I
could have a large block if/elif/else statements.
Is there any way to avoid that?

Only splitting the method into 2 or more parts. If that's not possible,
disable the warning.

 6) R:722:waitDiscretes: Too many local variables (38/15)
That's new to me. What is wrong with too many local variables?
Can anything be done to improve that besides having too many globals?

The more local variables you have, the more difficult the code is to
read. Or you use less variables, or you split the method into 2 or more
parts, or you disable the warning.

 7) W:933:sendStringToSocket: Redefining name 'nPortNumber' from outer scope
 (line
What is wrong with using the same variable name in a function that is
 used by its caller?

You are hiding something. For example, this code fails strangely (I know
this example isn't that good, but you get the idea):

files = glob('something/*')
for file in files:
# do_something 
filename = do_something_with_the_name(file)
# do_something_more
contents = file(filename).read() # fails here

 8) W:995:sendStringToSocket: Used builtin function 'map'
Is that a problem?

Sometimes it's slower than list comprehensions, sometimes it's less
legible than list comp. and IIRC GvR doesn't like it, but if you do,
disable the warning.

HTH,

-- 
Felipe.

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

Re: String To Dict Problem

2006-04-21 Thread Felipe Almeida Lessa
Em Sex, 2006-04-21 às 18:40 -0700, Clodoaldo Pinto escreveu:
 Only a small problem when I try to evaluate this:
 
 safe_eval('True')

Change

def visitName(self,node, **kw):
raise Unsafe_Source_Error(Strings must be quoted, 
 node.name, node)

To
otherNames = {
'True': True,
'False': False,
'None': None
}

def visitName(self, node, **kw):
name = node.name
try:
return self.__class__.otherNames[name]
except KeyError:
raise Unsafe_Source_Error(Strings must be quoted, 
  name, node)


-- 
Felipe.

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

Re: Generate a sequence of random numbers that sum up to 1?

2006-04-21 Thread Felipe Almeida Lessa
Em Sáb, 2006-04-22 às 03:16 +, Edward Elliott escreveu:
 If that level of accuracy 
 matters, you might consider generating your rands as integers and then 
 fp-dividing by the sum (or just store them as integers/fractions).

Or using decimal module: http://docs.python.org/lib/module-decimal.html

-- 
Felipe.

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

Re: Method Call in Exception

2006-04-19 Thread Felipe Almeida Lessa
Em Qua, 2006-04-19 às 16:54 -0700, mwt escreveu:
 This works when I try it, but I feel vaguely uneasy about putting
 method calls in exception blocks. 

What do you put in exception blocks?!


 So tell me, Brave Pythoneers, is this
 evil sorcery that I will end up regretting, or is it just plain good
 ol' Python magic?

IMHO, the exception block in Python is used a lot in places where you
could use an if-then-else, like your example that could be written as

if internet_available():
[...] #doing some internet stuff
else:
alternate_method_that_doesnt_need_internet()

So yes, I think there's no problem there.

-- 
Felipe.

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

Re: Uniquifying a list?

2006-04-18 Thread Felipe Almeida Lessa
Em Ter, 2006-04-18 às 10:31 -0500, Tim Chase escreveu:
 Is there an obvious/pythonic way to remove duplicates from a 
 list (resulting order doesn't matter, or can be sorted 
 postfacto)?  My first-pass hack was something of the form
 
   myList = [3,1,4,1,5,9,2,6,5,3,5]
   uniq = dict([k,None for k in myList).keys()
 
 or alternatively
 
   uniq = list(set(myList))
 
 However, it seems like there's a fair bit of overhead 
 here...creating a dictionary just to extract its keys, or 
 creating a set, just to convert it back to a list.  It feels 
 like there's something obvious I'm missing here, but I can't 
 put my finger on it.

Your list with 11 elements (7 unique):

$ python2.4 -mtimeit -s 'x = [3,1,4,1,5,9,2,6,5,3,5]' 'y = dict((k,None)
for k in x).keys()'
10 loops, best of 3: 8.01 usec per loop

$ python2.4 -mtimeit -s 'x = [3,1,4,1,5,9,2,6,5,3,5]' $'y = []\nfor i in
x:\nif i not in y:\ny.append(i)'
10 loops, best of 3: 5.43 usec per loop

$ python2.4 -mtimeit -s 'x = [3,1,4,1,5,9,2,6,5,3,5]' 'y = list(set(x))'
10 loops, best of 3: 3.57 usec per loop



A list with 100 000 elements (1 000 unique):

$ python2.4 -mtimeit -s 'x = range(1000) * 100' $'y = []\nfor i in x:\n
if i not in y:\ny.append(i)'
10 loops, best of 3: 2.12 sec per loop

$ python2.4 -mtimeit -s 'x = range(1000) * 100' 'y = dict((k,None) for k
in x).keys()'
10 loops, best of 3: 32.2 msec per loop

$ python2.4 -mtimeit -s 'x = range(1000) * 100' 'y = list(set(x))'
100 loops, best of 3: 6.09 msec per loop



list(set(x)) is the clear winner with almost O(1) performance.
*However*, can't you always use set or frozenset instead of
converting back and forth?


HTH,

-- 
Felipe.

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

Re: extracting a substring

2006-04-18 Thread Felipe Almeida Lessa
Em Ter, 2006-04-18 às 17:25 -0700, [EMAIL PROTECTED] escreveu:
 Hi,
 I have a bunch of strings like
 a53bc_531.txt
 a53bc_2285.txt
 ...
 a53bc_359.txt
 
 and I want to extract the numbers 531, 2285, ...,359.

Some ways:

1) Regular expressions, as you said:
 from re import compile
 find = compile(a53bc_([1-9]*)\\.txt).findall
 find('a53bc_531.txt\na53bc_2285.txt\na53bc_359.txt')
['531', '2285', '359']

2) Using ''.split:
 [x.split('.')[0].split('_')[1] for x in 'a53bc_531.txt
\na53bc_2285.txt\na53bc_359.txt'.splitlines()]
['531', '2285', '359']

3) Using indexes (be careful!):
 [x[6:-4] for x in 'a53bc_531.txt\na53bc_2285.txt
\na53bc_359.txt'.splitlines()]
['531', '2285', '359']

Measuring speeds:

$ python2.4 -m timeit -s 'from re import compile; find =
compile(a53bc_([1-9]*)\\.txt).findall; s = a53bc_531.txt
\na53bc_2285.txt\na53bc_359.txt' 'find(s)'
10 loops, best of 3: 3.03 usec per loop

$ python2.4 -m timeit -s 's = a53bc_531.txt\na53bc_2285.txt
\na53bc_359.txt\n[:-1]' [x.split('.')[0].split('_')[1] for x in
s.splitlines()]
10 loops, best of 3: 7.64 usec per loop

$ python2.4 -m timeit -s 's = a53bc_531.txt\na53bc_2285.txt
\na53bc_359.txt\n[:-1]' [x[6:-4] for x in s.splitlines()]
10 loops, best of 3: 2.47 usec per loop


$ python2.4 -m timeit -s 'from re import compile; find =
compile(a53bc_([1-9]*)\\.txt).findall; s = (a53bc_531.txt
\na53bc_2285.txt\na53bc_359.txt\n*1000)[:-1]' 'find(s)'
1000 loops, best of 3: 1.95 msec per loop

$ python2.4 -m timeit -s 's = (a53bc_531.txt\na53bc_2285.txt
\na53bc_359.txt\n * 1000)[:-1]' [x.split('.')[0].split('_')[1] for x
in s.splitlines()]
100 loops, best of 3: 6.51 msec per loop

$ python2.4 -m timeit -s 's = (a53bc_531.txt\na53bc_2285.txt
\na53bc_359.txt\n * 1000)[:-1]' [x[6:-4] for x in s.splitlines()]
1000 loops, best of 3: 1.53 msec per loop


Summary: using indexes is less powerful than regexps, but faster.

HTH,

-- 
Felipe.

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

Re: filling today's date in a form

2006-04-16 Thread Felipe Almeida Lessa
Em Dom, 2006-04-16 às 19:22 -0400, Kun escreveu:
 i have a form 

Which kind of form? Which toolkit?

 which takes in inputs for a mysql query. one of the inputs 
 is 'date'.  normally, a user has to manually enter a date, 

Enter the date in which kind of control?

 but i am 
 wondering if there is a way to create a button which would automatically 
 insert today's date in the date form field if the user chooses to use 
 today's date.

Almost 100% sure that there is, but I can't tell you if or how if you
don't tell us how you are doing what you are doing.

-- 
Felipe.

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

Re: How to Convert a string into binary

2006-04-15 Thread Felipe Almeida Lessa
Em Sáb, 2006-04-15 às 19:25 +, HNT20 escreveu:
 is there a way to convert a string into its binary representation of the 
 ascii table.??

I'm very curious... why?

And no, I don't have the answer.

-- 
Felipe.

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

Re: How to Convert a string into binary

2006-04-15 Thread Felipe Almeida Lessa
Em Sáb, 2006-04-15 às 18:09 -0400, Terry Reedy escreveu:
 # given string s
 binchars = []
 for c in s: binchars.append(a2b[ord(c)])

Faster:

binchars = [a2b[ord(c)] for c in s]

-- 
Felipe.

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

Re: requestion regarding regular expression

2006-04-14 Thread Felipe Almeida Lessa
Em Sex, 2006-04-14 às 07:47 -0700, BartlebyScrivener escreveu:
 starts = [i for i, line in enumerate(lines) if
 line.startswith('(defun')]

This line makes a list of integers. enumerate gives you a generator that
yields tuples consisting of (integer, object), and by i for i, line
you unpack the tuple into (i, line) and pick just i.

 for i, start in starts:

Here you try to unpack the elements of the list starts into (i,
start), but as we saw above the list contains just i, so an exception
is raised. 

I don't know what you want, but...

starts = [i, line for i, line in enumerate(lines) if
line.startswith('(defun')]

or

starts = [x for x in enumerate(lines) if x[1].startswith('(defun')]

...may (or may not) solve your problem.

-- 
Felipe.

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

Re: zlib and zip files

2006-04-14 Thread Felipe Almeida Lessa
Em Sex, 2006-04-14 às 17:14 +0200, Jan Prochazka escreveu:
 Here is my module for parsing zip files:

1) Have you checked the source of Python's zipfile module?

 import struct, zlib
 
 class ZipHeaderEntry:
 name = ''
 offset = 0
 uncomlen = 0
 comlen = 0

2) You know that those variables are *class* vars, not instance vars,
right?

3) I didn't read your code, but have you considered
http://pyconstruct.sourceforge.net/ ?

-- 
Felipe.

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

Re: PEP 359: The make Statement

2006-04-14 Thread Felipe Almeida Lessa
Em Sex, 2006-04-14 às 09:31 -0600, Steven Bethard escreveu:
 [1] Here's the code I used to test it.
 
   def make(callable, name, args, block_string):
 ... try:
 ... make_dict = callable.__make_dict__
 ... except AttributeError:
 ... make_dict = dict
 ... block_dict = make_dict()
 ... exec block_string in block_dict
 ... return callable(name, args, block_dict)
 ...
   (snip)

I think it would be nice not to put those  and ... to make copy
and paste easier. Okay, I know we can do .join(line[4:] for line in
text), but that's just my humble opinion.

-- 
Felipe.

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

Re: instance variable weirdness

2006-04-14 Thread Felipe Almeida Lessa
Em Sex, 2006-04-14 às 09:18 -0700, wietse escreveu:
 def __init__(self, name, collection=[]):

Never, ever, use the default as a list.

 self.collection = collection

This will just make a reference of self.collection to the collection
argument.

 inst.collection.append(i)

As list operations are done in place, you don't override the
self.collection variable, and all instances end up by having the same
list object.

To solve your problem, change 
def __init__(self, name, collection=[]):
BaseClass.__init__(self)
self.name = name
self.collection = collection # Will reuse the list
to
def __init__(self, name, collection=None):
BaseClass.__init__(self)
self.name = name
if collection is None:
collection = [] # Will create a new list on every instance
self.collection = collection


-- 
Felipe.

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

Re: instance variable weirdness

2006-04-14 Thread Felipe Almeida Lessa
Em Sex, 2006-04-14 às 13:30 -0300, Felipe Almeida Lessa escreveu:
 To solve your problem, change 
 def __init__(self, name, collection=[]):
 BaseClass.__init__(self)
 self.name = name
 self.collection = collection # Will reuse the list
 to
 def __init__(self, name, collection=None):
 BaseClass.__init__(self)
 self.name = name
 if collection is None:
 collection = [] # Will create a new list on every instance
 self.collection = collection

Or if None is valid in your context, do:

__marker = object()
def __init__(self, name, collection=__marker):
BaseClass.__init__(self)
self.name = name
if collection is __marker:
collection = [] # Will create a new list on every instance
self.collection = collection

-- 
Felipe.

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

Re: instance variable weirdness

2006-04-14 Thread Felipe Almeida Lessa
Em Sáb, 2006-04-15 às 04:03 +1000, Steven D'Aprano escreveu:
 Sometimes you want the default to mutate each time it is used, for example
 that is a good technique for caching a result:
 
 def fact(n, _cache=[1, 1, 2]):
 Iterative factorial with a cache.
 try:
 return _cache[n]
 except IndexError:
 start = len(_cache)
 product = _cache[-1]
 for i in range(start, n+1):
 product *= i
 _cache.append(product)
 return product

I prefer using something like this for the general case:

def cached(function):
Decorator that caches the function result.

There's only one caveat: it doesn't work for keyword arguments.

cache = {}
def cached_function(*args):
This is going to be replaced below.
try:
return cache[args]
except KeyError:
cache[args] = function(*args)
return cache[args]
cached_function.__doc__ = function.__doc__
cached_function.__name__ = function.__name__
return cached_function



And for this special case, something like:

def fact(n):
Iterative factorial with a cache.
cache = fact.cache
try:
return cache[n]
except IndexError:
start = len(cache)
product = cache[-1]
for i in range(start, n+1):
product *= i
cache.append(product)
return product
fact.cache = [1, 1, 2]



This may be ugly, but it's less error prone. Also, we don't expose the
cache in the function's argument list.

-- 
Felipe.

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

Re: Writing backwards compatible code

2006-04-14 Thread Felipe Almeida Lessa
Em Sex, 2006-04-14 às 13:28 -0500, Robert Kern escreveu:
 Steven D'Aprano wrote:
  I came across an interesting (as in the Chinese curse) problem today. I
  had to modify a piece of code using generator expressions written with
  Python 2.4 in mind to run under version 2.3, but I wanted the code to
  continue to use the generator expression if possible.
 
 Why? AFAICT, it really is just syntactic sugar. Very nice syntactic sugar, but
 not necessary at all. If you are going to have the ugly, syntactically bitter
 version in your code anyways, why clutter up your code even more trying to do 
 both?

Right. You can always use classes.

-- 
Felipe.

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

Re: skip item in list for loop

2006-04-14 Thread Felipe Almeida Lessa
Em Sex, 2006-04-14 às 20:33 +0200, Diez B. Roggisch escreveu:
 def read_lines(inFile):
  fg = iter(inFile)
  for line in fg:
  if pmos4_highv in line:
  fg.next()
  else:
  yield line

Just be aware that the fb.next() line can raise an StopIteration
exception that would otherwise be caught by the for loop. If you have
any resources that need to be cleaned up, try...finally is you friend.

-- 
Felipe.

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

Re: Writing backwards compatible code

2006-04-14 Thread Felipe Almeida Lessa
Em Sex, 2006-04-14 às 13:37 -0500, Robert Kern escreveu:
 Felipe Almeida Lessa wrote:
  Em Sex, 2006-04-14 às 13:28 -0500, Robert Kern escreveu:
  
 Steven D'Aprano wrote:
 
 I came across an interesting (as in the Chinese curse) problem today. I
 had to modify a piece of code using generator expressions written with
 Python 2.4 in mind to run under version 2.3, but I wanted the code to
 continue to use the generator expression if possible.
 
 Why? AFAICT, it really is just syntactic sugar. Very nice syntactic sugar, 
 but
 not necessary at all. If you are going to have the ugly, syntactically 
 bitter
 version in your code anyways, why clutter up your code even more trying to 
 do both?
  
  Right. You can always use classes.
 
 Well, I guess you could, but using actual generators would be much cleaner.

That's the whole point around syntactic sugar: being cleaner, more
concise, (sometimes) less error-prone and (less times) faster.

-- 
Felipe.

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

Re: Problem involving sets...

2006-04-14 Thread Felipe Almeida Lessa
Em Sex, 2006-04-14 às 15:43 -0700, flamesrock escreveu:
 Does anyone have a simple solution

$ python2.4
Python 2.4.3 (#2, Mar 30 2006, 21:52:26)
[GCC 4.0.3 (Debian 4.0.3-1)] on linux2
Type help, copyright, credits or license for more information.
 l1 = [['c1',1],['c2',2],['c3',4]]
 l2 = [['c1',1],['c2',2],['c4',4],['c3',3]]
 print [tuple(x) for x in l1]
[('c1', 1), ('c2', 2), ('c3', 4)]
 print [tuple(x) for x in l2]
[('c1', 1), ('c2', 2), ('c4', 4), ('c3', 3)]
 s1 = frozenset(tuple(x) for x in l1)
 s2 = frozenset(tuple(x) for x in l2)
 print s1
frozenset([('c2', 2), ('c1', 1), ('c3', 4)])
 print s2
frozenset([('c2', 2), ('c4', 4), ('c3', 3), ('c1', 1)])
 print s2-s1
frozenset([('c4', 4), ('c3', 3)])
 print [list(x) for x in s2-s1]
[['c4', 4], ['c3', 3]]


-- 
Felipe.

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

Re: Remove Whitespace

2006-04-13 Thread Felipe Almeida Lessa
Em Sex, 2006-04-14 às 12:46 +1000, Steven D'Aprano escreveu:
 Why would you want to call in the heavy sledgehammer of regular
 expressions for cracking this peanut?

And put heavy on that!

$ python2.4 -mtimeit -s str = 'D c a V e r \ = d w o r d : 0 0 0 0 0 6
4 0' 'str.replace( , )'
10 loops, best of 3: 3.07 usec per loop
$ python2.4 -mtimeit -s str = 'D c a V e r \ = d w o r d : 0 0 0 0 0 6
4 0' '.join(str.split())'
10 loops, best of 3: 4.16 usec per loop
$ python2.4 -mtimeit -s from re import sub; str = 'D c a V e r \ = d w
o r d : 0 0 0 0 0 6 4 0' 'sub(\\s, , str)'
1 loops, best of 3: 23.6 usec per loop
$ calc 23.6 / 3.07
~7.68729641693811074919

I couldn't be expressed better:

Some people, when confronted with a problem, think I know, I'll use
regular expressions. Now they have two problems.
  — Jamie Zawinski, in comp.lang.emacs

-- 
Felipe.

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

Re: PEP 359: The make Statement

2006-04-13 Thread Felipe Almeida Lessa
Em Qui, 2006-04-13 às 23:17 -0400, Nicolas Fleury escreveu:
 The callable could have something like a __namespacetype__ that could be 
 use instead of dict.  That type would have to implement __setitem__.

Or the namespace variable could be a list of tuples.

-- 
Felipe.

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

Re: list.clear() missing?!?

2006-04-13 Thread Felipe Almeida Lessa
Em Sex, 2006-04-14 às 09:17 +0400, Sergei Organov escreveu:
 I, as a newcomer, don't have much trouble understanding the binding vs
 the assignment by themselves. What does somewhat confuse is dual role of
 the = operator, -- sometimes it means bind and other times it means
 assign, right? For me it seems that the language would be less
 error-prone and easier to grok if these two operations had different
 names/syntax (thinking about lisp let vs set), though it seems to be
 too drastic change even for Python3000.

The = operator *always* binds.

-- 
Felipe.

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

Re: reading files in small chunks?

2006-04-13 Thread Felipe Almeida Lessa
Em Sex, 2006-04-14 às 13:45 +0800, Rajesh Sathyamoorthy escreveu:
 I wanted to know why it is more efficient to read a file in smaller
 chunks ( using file() or open() )?

It's more efficient in some cases, and worse on others. It also depends
on how you implement the read loop. I won't elaborate too much here,
there are loads of sites and books that talk about this topic.

 If this is not done, will this lead to errors in the data read or just
 results in slower performance?

It doesn't corrupt anything, unless you have a buggy hardware.

-- 
Felipe.

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

Re: list.clear() missing?!?

2006-04-12 Thread Felipe Almeida Lessa
Em Qua, 2006-04-12 às 12:40 -0700, Raymond Hettinger escreveu:
 * the existing alternatives are a bit perlish

I love this argument =D! perlish... lol...

Cheers,

-- 
Felipe.

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

Re: Why new Python 2.5 feature class C() return old-style class ?

2006-04-11 Thread Felipe Almeida Lessa
Em Ter, 2006-04-11 às 06:49 -0700, looping escreveu:
 But in an other hand,
 I believe that new-style class are faster to instanciate (maybe I'm
 wrong...).

$ python2.4 -m timeit -s 'class x: pass' 'x()'
100 loops, best of 3: 0.435 usec per loop
$ python2.4 -m timeit -s 'class x(object): pass' 'x()'
100 loops, best of 3: 0.316 usec per loop

-- 
Felipe.

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

Re: Why new Python 2.5 feature class C() return old-style class ?

2006-04-11 Thread Felipe Almeida Lessa
Em Ter, 2006-04-11 às 07:17 -0700, Aahz escreveu:
 Can, yes.  But should it?  The whole point of adding the () option to
 classes was to ease the learning process for newbies who don't
 understand why classes have a different syntax from functions.  Having
 
 class C(): pass
 
 behave differently from
 
 class C: pass
 
 would be of no benefit for that purpose.

Why should a newbie use an old-style class?

-- 
Felipe.

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

Re: list.clear() missing?!?

2006-04-11 Thread Felipe Almeida Lessa
Em Ter, 2006-04-11 às 10:42 -0600, Steven Bethard escreveu:
 one of::
 
  del lst[:]
 
  lst[:] = []
 
 or if you don't need to modify the list in place,
 
  lst = []
 
 Personally, I tend to go Fredrik's route and use the first.

I love benchmarks, so as I was testing the options, I saw something very
strange:

$ python2.4 -mtimeit 'x = range(10); '
100 loops, best of 3: 6.7 msec per loop
$ python2.4 -mtimeit 'x = range(10); del x[:]'
100 loops, best of 3: 6.35 msec per loop
$ python2.4 -mtimeit 'x = range(10); x[:] = []'
100 loops, best of 3: 6.36 msec per loop
$ python2.4 -mtimeit 'x = range(10); del x'
100 loops, best of 3: 6.46 msec per loop

Why the first benchmark is the slowest? I don't get it... could someone
test this, too?

Cheers,

-- 
Felipe.

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

Re: Manipulating sets from the 2.4 C API?

2006-04-11 Thread Felipe Almeida Lessa
Em Ter, 2006-04-11 às 18:55 +0200, Martin v. Löwis escreveu:
 Dave Opstad wrote:
  If I want to handle sets should I just use a dictionary's keys and 
  ignore the values, or is there some more explicit set support somewhere 
  I'm not seeing?
 
 Indeed, there is. To create a new set, do
 
PyObject_Call(PySet_Type, );
 
 To, say, invoke the add method, do
 
PyObject_CallMethod(s, add, O, o);

I don't know much about the C API, but I'll ask anyway: the methods,
say, PySet, would be included for clarity/brevity or for performance
reasons?

-- 
Felipe.

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

Re: list.clear() missing?!?

2006-04-11 Thread Felipe Almeida Lessa
Em Ter, 2006-04-11 às 17:56 +, John Salerno escreveu:
 Steven Bethard wrote:
 
 
  lst[:] = []
  lst = []
 
 What's the difference here?

lst[:] = [] makes the specified slice become []. As we specified :, it
transforms the entire list into [].

lst = [] assigns the value [] to the variable lst, deleting any previous
one.

This might help:

 lst = range(10)
 id(lst), lst
(-1210826356, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
 lst[:] = []
 id(lst), lst
(-1210826356, [])

 lst = range(10)
 id(lst), lst
(-1210844052, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
 lst = []
 id(lst), lst
(-1210826420, [])


You see? lst[:] removes all elements from the list that lst refers to,
while lst = [] just creates a new list and discard the only one. The
difference is, for example:

 lst = range(3)
 x = [lst, lst, lst]
 x
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]
 lst[:] = []
 x
[[], [], []]

 lst = range(3)
 x = [lst, lst, lst]
 x
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]
 lst = []
 x
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]

HTH,

-- 
Felipe.

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

Re: Memory limit to dict?

2006-04-11 Thread Felipe Almeida Lessa
Em Ter, 2006-04-11 às 19:45 +0200, Peter Beattie escreveu:
 I was wondering whether certain data structures in Python, e.g. dict,
 might have limits as to the amount of memory they're allowed to take up.
 Is there any documentation on that?
 
 Why am I asking? I'm reading 3.6 GB worth of BLAST output files into a
 nested dictionary structure (dict within dict ...). Looks something like
 this:
 
 { GenomeID:
   { ProteinID:
 { GenomeID:
   { ProteinID, Score, PercentValue, EValue } } } }

I don't have the answer to your question and I'll make a new one: isn't
the overhead (performance and memory) of creating dicts too large to be
used in this scale? 

I'm just speculating, but I *think* that using lists and objects may be
better.

My 2 cents,

-- 
Felipe.

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

Re: list.clear() missing?!?

2006-04-11 Thread Felipe Almeida Lessa
Em Qua, 2006-04-12 às 11:36 +1000, Steven D'Aprano escreveu:
 On Tue, 11 Apr 2006 19:15:18 +0200, Martin v. Löwis wrote:
 
  Felipe Almeida Lessa wrote:
  I love benchmarks, so as I was testing the options, I saw something very
  strange:
  
  $ python2.4 -mtimeit 'x = range(10); '
  100 loops, best of 3: 6.7 msec per loop
  $ python2.4 -mtimeit 'x = range(10); del x[:]'
  100 loops, best of 3: 6.35 msec per loop
  $ python2.4 -mtimeit 'x = range(10); x[:] = []'
  100 loops, best of 3: 6.36 msec per loop
  $ python2.4 -mtimeit 'x = range(10); del x'
  100 loops, best of 3: 6.46 msec per loop
  
  Why the first benchmark is the slowest? I don't get it... could someone
  test this, too?
  
  In the first benchmark, you need space for two lists: the old one and
  the new one; 
 
 Er, what new list? I see only one list, x = range(10), which is merely
 created then nothing done to it. Have I missed something?

He's talking about the garbage collector.

Talking about the GC, do you want to see something *really* odd?

$ python2.4 -mtimeit -s 'from gc import collect' 'collect(); x =
range(10); '
100 loops, best of 3: 13 msec per loop

$ python2.4 -mtimeit -s 'from gc import collect' 'collect(); x =
range(10); del x[:]'
100 loops, best of 3: 8.19 msec per loop

$ python2.4 -mtimeit -s 'from gc import collect' 'collect(); x =
range(10); x[:] = []'
100 loops, best of 3: 8.16 msec per loop

$ python2.4 -mtimeit -s 'from gc import collect' 'collect(); x =
range(10); del x'
100 loops, best of 3: 8.3 msec per loop


But in this case I got the answer (I think):
- When you explicitly delete the objects, the GC already know that it
can be collected, so it just throw the objects away.
- When we let the x variable continue to survive, the GC has to look
at all the 11 objects to see if they can be collected -- just to see
that it can't.

Also, IIRC del x is slower than x = [] because removing a name from
the namespace is more expensive than just assigning something else to
it. Right?

 I understood Felipe to be asking, why does it take longer to just create a
 list, than it takes to create a list AND then do something to it? 

I see dead people... ;-)

-- 
Felipe.

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

Re: python + access + odbc + linux

2006-04-10 Thread Felipe Almeida Lessa
Em Seg, 2006-04-10 às 10:38 -0500, Philippe Martin escreveu:
 I understand that access can be accessed through an ODBC driver under
 windows (instead of Jet).
 
 I am wondering if the same can be done under Linux.

As far as I know, no. But there is that http://mdbtools.sourceforge.net/
that may help you, but when I tried I had limited success.

Cheers,

-- 
Felipe.

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

Re: About classes and OOP in Python

2006-04-10 Thread Felipe Almeida Lessa
Em Seg, 2006-04-10 às 07:19 -0700, fyhuang escreveu:
 class PythonClass:
private foo = bar
private var = 42
allow_readwrite( [ foo, var ] )

You are aware that foo and var would become class-variables, not
instance-variables, right?

But you can always do:

class PythonClass(object):
def __init__(self):
self.__foo = bar

foo = property(lambda self: self.__foo)


And then:

 a = PythonClass()
 a.foo
'bar'
 a.foo = 'baz'
Traceback (most recent call last):
  File stdin, line 1, in ?
AttributeError: can't set attribute


But you can also bypass this security:

 a._PythonClass__foo = 'baz'
 a.foo
'baz'


But this was not a mistake, nobody mistakenly writes _PythonClass__.

 Or allow_read to only allow read-only access. Also there might be a
 way to implement custom getters and setters for those times you want
 to modify input or something:
 
 class PythonClass:
def get foo():
return bar
 
def set var( value ):
var = value

There's a PEP somewhere that proposes things like (same example I gave
earlier):

class PythonClass(object):
def __init__(self):
self.__foo = bar

create property foo:
def get(self):
return self.__foo

-- 
Felipe.

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

Re: Is this code snippet pythonic

2006-04-10 Thread Felipe Almeida Lessa
Em Seg, 2006-04-10 às 03:52 -0700, [EMAIL PROTECTED] escreveu:
 My Tead  Lead  my object counter  code seen below is not  pythonic

As Peter said, you should really ask your Tead Lead, but what about:

class E(object):
Holds a class-wide counter incremented when it's instantiated.
count = 0

def __init__(self):
# One instance, increment the counter
E.count += 1


def  test():
Test the counter class E.
e1 = E()
assert e1.count == 1
print e1.count

e2 = E()
assert e2.count == 2
print e2.count

e3 = E()
assert e3.count == 3
print e3.count

if __name__ == '__main__':
test()

-- 
Felipe.

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

Re: how to make a generator use the last yielded value when it regains control

2006-04-10 Thread Felipe Almeida Lessa
Em Seg, 2006-04-10 às 10:05 -0700, Lonnie Princehouse escreveu:
 I happen to think the recursive version is more elegant, but that's
 just me ;-)

It may be elegant, but it's not efficient when you talk about Python.
Method calls are expensive:

$ python2.4 -mtimeit 'pass'
1000 loops, best of 3: 0.0585 usec per loop
$ python2.4 -mtimeit -s 'def x(): pass' 'x()'
100 loops, best of 3: 0.291 usec per loop
$ calc 0.291/0.0585
~4.97435897435897435897
$ calc 0.291-0.0585
0.2325


This happens because of the dynamic nature of Python and its lack of
tail call optimization. IOW, avoid recursive methods when possible (I
usually write those for the first version of a method then rethink it
using a non-recursive approach), specially if they are part of a hot
spot.

-- 
Felipe.

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

Re: unboundlocalerror with cgi module

2006-04-10 Thread Felipe Almeida Lessa
Em Seg, 2006-04-10 às 11:29 -0700, David Bear escreveu:
 However, the except block does not seem to catch the exception and an
 unboundlocalerror is thrown anyway. What am I missing?

See http://docs.python.org/tut/node10.html :


A try statement may have more than one except clause, to specify
handlers for different exceptions. At most one handler will be executed.
Handlers only handle exceptions that occur in the corresponding try
clause, not in other handlers of the same try statement. An except
clause may name multiple exceptions as a parenthesized tuple, for
example:

... except (RuntimeError, TypeError, NameError):
... pass


-- 
Felipe.

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

  1   2   3   >