Re: SV: Changing the size of a Button

2008-03-09 Thread Marc 'BlackJack' Rintsch
On Sun, 09 Mar 2008 19:45:58 +0100, K Viltersten wrote:

 What i wish to do is to affect the size 
 of the button but not due to change of 
 text but due to resize of the frame it
 resides in.
 
 This far i've managed to get a callback 
 to a function as the resize occurs and to
 print the sizes. However, i'd like to 
 assign these values to the button so it 
 always stays the same width as the frame.

Don't do it yourself, pack with the `fill` argument set to `Tkinter.X`.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Classes and modules are singletons?

2008-03-06 Thread Marc 'BlackJack' Rintsch
On Thu, 06 Mar 2008 11:06:50 -0800, castironpi wrote:

 On Mar 6, 8:30 am, Carl Banks [EMAIL PROTECTED] wrote:
 Anyway, the answer to what you are probably asking is No.  Try this:

 import module
 c1 = module.Someclass
 reload(module)
 c2 = module.Someclass
 c1 is c2
 
 What about
 
 o= object()
 b1= o.someattr
 reload( o )
 b2= o.someattr
 b1 is b2
 
 ?

You are really a bit thick, a troll, or a bot.

*plonk*

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Can one get for x in y to work for non builtin classes?

2008-03-03 Thread Marc 'BlackJack' Rintsch
On Mon, 03 Mar 2008 12:17:39 +0100, M.-A. Lemburg wrote:

 It's also possible to implement .__getitem__() and .__len__()
 methods and have Python create an iterator on-the-fly. That's
 how Python used to work before iterators were added to the
 language.

A suitable `__getitem__()` is enough.  The end will be signaled by an
`IndexError`.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help needed with regex and unicode

2008-03-03 Thread Marc 'BlackJack' Rintsch
On Tue, 04 Mar 2008 10:49:54 +0530, Pradnyesh Sawant wrote:

 I have a file which contains chinese characters. I just want to find out
 all the places that these chinese characters occur.
 
 The following script doesn't seem to work :(
 
 **
 class RemCh(object):
 def __init__(self, fName):
 self.pattern = re.compile(r'[\u2F00-\u2FDF]+')
 fp = open(fName, 'r')
 content = fp.read()
 s = re.search('[\u2F00-\u2fdf]', content, re.U)
 if s:
 print s.group(0)
 if __name__ == '__main__':
 rc = RemCh('/home/pradnyesh/removeChinese/delFolder.php')
 **
 
 the php file content is something like the following:
 
 **
 // Check if the folder still has subscribed blogs
 $subCount = function1($param1, $param2);
 if ($subCount  0) {
 $errors['summary'] = 'æ­ï½ æ½å¤此åï«åéé§ç²è';
 $errorMessage  = 'æ­ï½ æ½å¤此åï«åéé§ç²è';
 }

Looks like an UTF-8 encoded file viewed as ISO-8859-1.  Sou you should
decode `content` to unicode before searching the chinese characters.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: First post from a Python newbiw

2008-03-02 Thread Marc 'BlackJack' Rintsch
On Sun, 02 Mar 2008 14:15:09 +, Steve Turner wrote:

 Apart from doing something like
 a=[0,0,0]
 b=[0,0,0]
 c=[0,0,0]
 d=[a,b,c]
 
 is there a better way of creating d??

a = [[0] * 3 for dummy in xrange(3)]

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: First post from a Python newbiw

2008-03-02 Thread Marc 'BlackJack' Rintsch
On Sun, 02 Mar 2008 21:58:31 +0100, Christoph Zwerschke wrote:

 Marc 'BlackJack' Rintsch schrieb:
 On Sun, 02 Mar 2008 14:15:09 +, Steve Turner wrote:
 
 Apart from doing something like
 a=[0,0,0]
 b=[0,0,0]
 c=[0,0,0]
 d=[a,b,c]

 is there a better way of creating d??
 
 a = [[0] * 3 for dummy in xrange(3)]
 
 Why not simply [[0]*3]*3 ?

Because:

In [77]: a = [[0] * 3] * 3

In [78]: a
Out[78]: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

In [79]: a[0][0] = 42

In [80]: a
Out[80]: [[42, 0, 0], [42, 0, 0], [42, 0, 0]]

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is it possible to return a variable and use it...?

2008-03-02 Thread Marc 'BlackJack' Rintsch
On Sun, 02 Mar 2008 20:15:10 -0800, Nathan Pinno wrote:

 Hello all,
 
 Is it possible to return a variable and then use it like the
 following:
 [code]
 dir exp_1:
 while hen != *
sum = sum + hen
 return sum
 
 dir exp_2:
if sum = total_needed:
  print Profit can be made.
else:
  print Expect a loss.
 
 total_needed = int(raw_input(What is the total eggs needed? ))
 hen = int(raw_input(How many eggs did each hen lay? Enter them in 1
 by 1 or enter * when done. ))
 exp_1
 exp_2
 
 [/code]
 
 If not, then how do I do so?

Please work through the tutorial, then try to write actual Python code and
come back if you have problems with your implementation of the program. 
Show us the real code and a description of either what error message you
get, with full traceback, or if it does not raise an exception but just
does not what you excpect it to do, tell us what you expected and what you
get instead.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Character Problem

2008-03-02 Thread Marc 'BlackJack' Rintsch
On Mon, 03 Mar 2008 04:27:52 +0200, Harun BAYKAL wrote:

 I am studying on an addon developed for QGIS, a GIS software. But I
 have a problem. The extension has been developed with QT and Python.
 Actually Python is used for the interface design. For the user
 interface Python reads some values from some database files. I am not
 experienced Python user and the first developer of the addon had
 written the python codes for his database. And his database
 doesn't include any characters than the usual characaters. But my
 database file contains many characters which are not used in English.
 So I can not compile the extension because Python can not read the
 database files.
 
 So how can I change the python files for making it to read the
 databases without modifying the database. Otherwise I had to clear all
 the non usual characters from the database file which means most of
 the names and strings will be wrong. So somehow I had to make the
 python files to read the other unicode and non english characters?
 Anybody have any idea about how I can I fix such a problem.

All I get from this description is, that you have a problem with encodings
but what is the *specific* problem?  Where does the program fail?  With
what exception(s)?

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-03-01 Thread Marc 'BlackJack' Rintsch
On Fri, 29 Feb 2008 17:29:32 -0800, Lie wrote:

 On Feb 28, 10:00 am, Paul Rubin http://[EMAIL PROTECTED] wrote:
 More examples:

x = 1
y = len(s) + x

 = ok, decides that x is an int

x = 1
y = x + 3.0

 = ok, decides that x is a float

x = 1
y = x + 3.0
z = len(s) + x

 = forbidden, x cannot be an int and float at the same time.

  I am so glad you're not the designer of Python.

 This is how Haskell works and I don't notice much complaints about it.
 
 Ok, that means the line y = x + 3.0 have a side effect of x =
 float(x)? I think I would say that is an implicit behavior.

But the type of `x` must be specialized somehow.  `x` doesn't start as
`Int` or `Integer` but the very generic and AFAIK abstract type class `Num`.

After seeing the second line the compiler finds an implementation for `+`
and the type class `Fractional` for both operands and now thinks `x` must
be a `Fractional`, a subclass of `Num`.

Then comes the third line with `length` returning an `Int` and the
`Fractional` `x` but there is no implementation for a `+` function on
those types.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mod_python Unable to create file

2008-03-01 Thread Marc 'BlackJack' Rintsch
On Sat, 01 Mar 2008 22:47:02 -0800, kaush wrote:

 I am using Apache and mod_python to service POST/GET requests on MAC
 OS. My script tries to create a file
 
 file = open(file_path, 'w')
 
 This fails with the following error
 
 EACCES
 Permission denied
 
 What is missing?

To state the ovious: the rights to create a file at `file_path`.  Remember
that web servers usually have their own user.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythons Ladders

2008-02-28 Thread Marc 'BlackJack' Rintsch
On Thu, 28 Feb 2008 10:34:45 -0800, Jeff Schwab wrote:

 Hey a flame bait.  I'll bite.
 
 Excuse me?  Somebody posts about an introductory course on C++ covering 
 dynamic arrays using pointers and literally says kill me now, and 
 I'm the flamer for asking him not to hold the language responsible for 
 the bad course?
 
 
 This a bit of an overreaction unless you
 know what the course was about.
 
 It's supposed to be about C++, according to the OP.

Yeah, sorry I've read C.  Actually it's about a language called C
++ according to the OP.

 To the OP: If you try C++, don't hold that crappy language against C#, D,
 or Java.  ;-)
 
 What's the relevance of C#, D, or Java to the OP's post?

The same as C++ to the OP's post if he would have talked about C.  :-)

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: XML expat error

2008-02-28 Thread Marc 'BlackJack' Rintsch
On Thu, 28 Feb 2008 12:37:10 -0800, dirkheld wrote:

 Yes of course: handle the exception instead of letting it propagate to the
 top level and ending the program.
 
 Ehm, maybe a stupid question... how. I'm rather new to python and I
 never user error handling.

Then you should work through the tutorial in the docs, at least until
section 8.3 Handling Exceptions:

http://docs.python.org/tut/node10.html#SECTION001030

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythons Ladders

2008-02-27 Thread Marc 'BlackJack' Rintsch
On Wed, 27 Feb 2008 19:18:27 -0800, Jeff Schwab wrote:

 Benoit wrote:
 I've been teaching myself the python language over the past few months
 using Mark Lutz' Learning Python, 3ed.  Python is also the first
 programming language I've ever taken up.  I find the language easy to
 learn and rather productive in relation to the introductory course on C
 ++ I'd begun in January for fun @ school (we're practicing dynamic
 arrays using pointers... kill me now).
 
 Get a better teacher, if you can.  Please do me a personal favor:  Don't 
 hold the crappy course against C++.  For the record, you should never 
 have to manage dynamically allocated arrays manually, nor store pointers 
 to them.  Try the std::vector template, and post in comp.lang.c++ if 
 have any trouble.

Hey a flame bait.  I'll bite.  This a bit of an overreaction unless you
know what the course was about.  If the goal is to learn about the
computer and that basically everything is a number in the end, then C is a
good choice.  More portable than assembler but nearly as close to the
metal.

To the OP: If you try C++, don't hold that crappy language against C#, D,
or Java.  ;-)

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: XML expat error

2008-02-27 Thread Marc 'BlackJack' Rintsch
On Wed, 27 Feb 2008 14:02:25 -0800, dirkheld wrote:

 Something strange here. The xml file causing the problem has only 361
 lines. Isn't there a way to catch this error, ignore it and continu
 with the rest of the other files?

Yes of course: handle the exception instead of letting it propagate to the
top level and ending the program.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-02-27 Thread Marc 'BlackJack' Rintsch
On Wed, 27 Feb 2008 19:00:19 -0800, Paul Rubin wrote:

 Steven D'Aprano [EMAIL PROTECTED] writes:
 Okay, that's just insane, making distinctions between literals and 
 variables like that.
 
 1 + 1.0  # okay
 
 = Yes
 
 x = 1
 x + 1.0  # is this okay or not? who knows?
 
 = Yes, ok
 
 len('s') + 1.0  # forbidden
 
 Yes, forbidden.  
 
 More examples:
 
x = 1
y = len(s) + x
 
 = ok, decides that x is an int
 
x = 1
y = x + 3.0
 
 = ok, decides that x is a float
 
x = 1
y = x + 3.0
z = len(s) + x
 
 = forbidden, x cannot be an int and float at the same time.
 
 I am so glad you're not the designer of Python.
 
 This is how Haskell works and I don't notice much complaints about it.

Complain!  :-)

For implementing this in Python you have to carry an is allowed to be
coerced to float flag with every integer object to decide at run time if
it is an error to add it to a float or not.  Or you make Python into a
statically typed language like Haskell.  But then it's not Python anymore
IMHO.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dict.get and str.xsplit

2008-02-26 Thread Marc 'BlackJack' Rintsch
On Tue, 26 Feb 2008 06:02:12 -0800, bearophileHUGS wrote:

 This is a real difference, that has real impact on the programs I
 write, so I often use the if/else approach, despite the dict.get()
 method being semantically fitter and shorter.
 So can the dict.get() method be speed up? And if not, why?

I guess it's the method lookup that's the slow part.  Factor it out of the
loop and measure again::

adict_get = adict.get
for _ in xrange(M):
for k in keys1:
r = adict_get(k, None)
for k in keys2:
r = adict_get(k, None)

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Article of interest: Python pros/cons for the enterprise

2008-02-26 Thread Marc 'BlackJack' Rintsch
On Tue, 26 Feb 2008 05:23:11 -0800, Nicola Musatti wrote:

 At least in C++ resource management only becomes more complicated if you
 need more control.

I think this is the point where so many people here disagree.  I'm coming
from a garbage collection background in OOP programming.  In C++
resource management becomes instantly more complicated because I have to
think about memory management and must actively manage it in *every case*.
Writing code in a RAII style and using smart pointer templates is a cost
for me.  A cost that's quite high, because it feels completely wrong to
have to think about it and to write in that value style, because that
goes against my expectations/picture of OOP -- a graph of
independent/loosely coupled objects communicating with each other.  In
this sense C++ looks like a quite crippled and fragile OOP language to me.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-02-26 Thread Marc 'BlackJack' Rintsch
On Tue, 26 Feb 2008 04:29:18 -0800, Lie wrote:

 J Cliff Dyer:
 I'm in the camp that believes that 3/4 does indeed yield the integer 0,
 but should be spelled 3//4 when that is the intention.
 
 That's creepy for people that are new to programming and doesn't know
 how CPUs work and are used to general mathematics. That means most
 people. As programming language are now more accessible to regular
 people without specialized Computer Science degree, it is a just
 natural trend that computer arithmetic must be done in an expectable
 manner as seen by those general population not by people who holds a
 CS degree.

So why is it creepy then!?  ``3 // 4`` is for the people knowing about
integer division and ``3 / 4`` gives the expected result for those who
don't.  Those who don't know ``//`` can write ``int(3 / 4)`` to get the
same effect.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dict.get and str.xsplit

2008-02-26 Thread Marc 'BlackJack' Rintsch
On Tue, 26 Feb 2008 06:33:01 -0800, castironpi wrote:

 On Feb 26, 8:14 am, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote:
 On Tue, 26 Feb 2008 06:02:12 -0800, bearophileHUGS wrote:
  This is a real difference, that has real impact on the programs I
  write, so I often use the if/else approach, despite the dict.get()
  method being semantically fitter and shorter.
  So can the dict.get() method be speed up? And if not, why?

 I guess it's the method lookup that's the slow part.  Factor it out of the
 loop and measure again::

     adict_get = adict.get
     for _ in xrange(M):
         for k in keys1:
             r = adict_get(k, None)
         for k in keys2:
             r = adict_get(k, None)

 Ciao,
         Marc 'BlackJack' Rintsch
 
 Can't be.  The string 'get' is only hashed once, since it's hard-coded
 into the script, and looking it up can't be any slower than looking up
 __getitem__.

Within functions it is faster.  In the original code the `get` attribute is
looked up on the `adict` object twice in each loop iteration via hashing. 
In my code it is looked up once before the loop and within the loop the
local name `adict_get` isn't looked up but hardcoded as index into the
internal locals array of the function.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How about adding rational fraction to Python?

2008-02-26 Thread Marc 'BlackJack' Rintsch
On Tue, 26 Feb 2008 09:29:55 -0500, D'Arcy J.M. Cain wrote:

 If 3/4 ever returned 0.75 in any language I would drop that language.

Then prepare to drop Python from version 3 on:

Python 3.0a1 (py3k, Aug 31 2007, 21:20:42)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type help, copyright, credits or license for more information.
 3 / 4
0.75

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is there enough information?

2008-02-26 Thread Marc 'BlackJack' Rintsch
On Tue, 26 Feb 2008 09:13:35 -0800, castironpi wrote:

 Back home, the original post would be interesting, so I wrote it.

So you think of this group as your personal notepad.  That explains a lot.  :-/

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Return value of an assignment statement?

2008-02-24 Thread Marc 'BlackJack' Rintsch
On Sat, 23 Feb 2008 22:44:30 +, Tim Roberts wrote:

 Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote:
 
On Fri, 22 Feb 2008 11:00:17 -0800, Aahz wrote:

 It's just too convenient to be able to write
 
 L += ['foo']
 
 without rebinding L.

nitpickBut ``+=`` does rebind./nitpick
 
 Usually, but there's an exception for lists, which a specific
 implementation for += that calls append.  Or do I misunderstand you?

Terry Reedy showed the tuple proof, here's the read only property case::

 class A(object):
 def __init__(self):
 self._data = list()

 @property
 def data(self):
 return self._data

 a = A()
 a.data += [42]

Output::

 Traceback (most recent call last):
   File test.py, line 25, in module
 a.data += [42]
 AttributeError: can't set attribute

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Return value of an assignment statement?

2008-02-23 Thread Marc 'BlackJack' Rintsch
On Fri, 22 Feb 2008 11:00:17 -0800, Aahz wrote:

 It's just too convenient to be able to write
 
 L += ['foo']
 
 without rebinding L.

nitpickBut ``+=`` does rebind./nitpick

Doesn't matter in this case but we've had confused programmers asking
questions here when `L` is a class attribute and it's rebound to the
instance, or if they tried it on a list in a tuple.  Extending a list
that's a read only property doesn't work either.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple - looking for a way to do an element exists check..

2008-02-23 Thread Marc 'BlackJack' Rintsch
On Sat, 23 Feb 2008 17:19:47 -0800, thebjorn wrote:

 On Feb 23, 6:18 pm, Paul Hankin [EMAIL PROTECTED] wrote:

 IMO Jason's solution of testing containment in a generator is better
 (more readable).
 if element[0] not in (x[0] for x in a):
 a.append(element)
 
 It may be more readable (although that's debatable), but it always
 traverses the entire list.

The ``not in`` stops if the element is found.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Return value of an assignment statement?

2008-02-22 Thread Marc 'BlackJack' Rintsch
On Thu, 21 Feb 2008 21:28:25 -0800, Jeff Schwab wrote:

 So what is the variable?  Or is Python the first HLL I've ever heard 
 of that didn't have variables?

Relax, Python has variables.  It's just sometimes a good advice for people
coming from languages like C to forget about that term for a while because
they have the wrong impression of what variable means.  A variable in
programming languages is composed of a name, a memory location, possibly a
type and a value. In C-like languages, where you put values in named and
typed boxes, the memory location and type are attached to the name.  In
Python both belong to the value.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Acting like button are being pressed (BUT THEY ARE NOT) Please Help

2008-02-22 Thread Marc 'BlackJack' Rintsch
On Fri, 22 Feb 2008 06:48:37 -0800, mcsejung wrote:

 [snipped massive bit of code]

Sorry but dumping about 900 lines of code at people with no real question
in the message body and just sort of a question in the subject won't help
much to get answers.

Just a quick look at the code tells that it could use some loops to
refactor it into a **much** shorter piece of code.

Then get rid of the asterisk import, ``except``\s without a specific
exception to handle, and the``global`` statement before you repost the
problem.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting python docstings

2008-02-22 Thread Marc 'BlackJack' Rintsch
On Fri, 22 Feb 2008 03:53:27 -0800, Rufman wrote:

 On Feb 22, 10:36 am, Stefan Behnel [EMAIL PROTECTED] wrote:
 Rufman wrote:
  Does anyone know how to get docstrings (reStructuredText) out of
  python source code using docutils?

 Depends on what you mean with get ... out of. There are tools like epydoc
 that generate source code documentation, maybe that's what you mean?
 
 Yeah...something like that, but using docutils.

What is something like that?  If `epydoc` doesn't do what you want, then
*what* exactly *do* you want?  You know that `epydoc` supports
reStructuredText as markup language!?

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Return value of an assignment statement?

2008-02-22 Thread Marc 'BlackJack' Rintsch
On Fri, 22 Feb 2008 12:32:10 +, Steven D'Aprano wrote:

 On Fri, 22 Feb 2008 08:12:56 +, Marc 'BlackJack' Rintsch wrote:
 
 A variable in programming languages is composed of a name, a memory
 location, possibly a type and a value. In C-like languages, where you
 put values in named and typed boxes, the memory location and type are
 attached to the name.  In Python both belong to the value.
 
 But Python objects don't have names, so by your own definition, they
 aren't variables.

Exactly!  Names aren't variables.  The unit of a name, an address, and a
value are a variable.

 Names are associated with namespaces, not objects. A name must have one
 and only one object bound to it at any one time;

What is a binding when it's not an association between a name and an
object!?  So names are associated with objects.  There are no names
without objects in Python.  If a name is not bound to any object, how could
the name exist?  That would be like a dangling pointer, a beast that
doesn't exists in Python.

nitpickOkay there are local names that are known and therefore somehow
exist before they get bound, but that's IMHO an implementation
detail.nitpick

 objects on the other hand can be bound to one name, or no name, or a
 thousand names. The object itself has no way of knowing what names it is
 bound to, if any.
 
 Or, to put it another way... Python doesn't have variables.

It has.  You just can't substitute the term name with variable and
expect it to behave like in C.  A variable is not just the name but also
the value and the storage space and how those are connected.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Article of interest: Python pros/cons for the enterprise

2008-02-22 Thread Marc 'BlackJack' Rintsch
On Fri, 22 Feb 2008 04:48:28 -0800, Nicola Musatti wrote:

 On Feb 22, 12:07 pm, Paul Rubin http://[EMAIL PROTECTED] wrote:
 Nicola Musatti [EMAIL PROTECTED] writes:
  In C++ memory is just another resource which you can handle just like
  any other one, possibly using RAII.

 Ok, I'll bite.  Here's a straightforward Python expression:

a = [f(x) + g(y) for x,y in izip(m1, m2) if h(x,y).frob() == 7]

 Consider how many intermediate objects are being allocated in figuring
 out that listcomp.  Do you REALLY want to manage all the deallocation
 with something like RAII?
 
 
 What makes you think that a translation of a similar expression would
 involve explicit dynamic allocation at all? Barring bugs, here's an
 equivalent example:
 
 #include iostream
 #include map
 #include vector
 
 int f(int n) { return n * 2; }
 int g(int n) { return ( n * 2 ) + 1; }
 
 std::mapint, int izip(int i, int j) {
   std::mapint, int m;
   m[i] = j;
   m[j] = i;
   return m;
 }
 
 class A {
   int i, j;
 public:
   A(int ii, int jj) : i(ii), j(jj) {}
   int frob() { return i + j; }
 };
 
 A h(int i, int j) { return A(i, j); }
 
 int main() {
   int m1 = 3;
   int m2 = 4;
   std::vectorint a;
   std::mapint, int m = izip(m1, m2);
   for ( std::mapint,int::iterator i = m.begin(); i != m.end(); ++i )
   {
   if ( h(i-first, i-second).frob() == 7 )
   a.push_back(f(i-first) + g(i-second));
   }
   for ( std::vectorint::iterator i = a.begin(); i != a.end(); ++i )
   std::cout  *i  '\n';
 }
 
 As you can see the standard library takes care of all memory
 management.

Aaah, that's much nicer and easier to understand than the list
comprehension.  After this great example I'll switch to C++.  ;-)

But somehow you still manage memory by writing in a style that favors
value types.

SCNR,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's the standard for code docs?

2008-02-20 Thread Marc 'BlackJack' Rintsch
On Tue, 19 Feb 2008 16:37:23 -0800, Preston  Landers wrote:

 On Feb 19, 4:31 pm, [EMAIL PROTECTED] wrote:
 
 But after reading some of your other recent posts on other topics, I'm
 not confident that it was intended to make sense at all.

Have a little bit patience, the bot is still in its early learning phase.  ;-)

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter Confusion

2008-02-17 Thread Marc 'BlackJack' Rintsch
On Sun, 17 Feb 2008 11:36:25 -0800, MartinRinehart wrote:

 Everything I've read about Tkinter says you create your window and
 then call its mainloop() method. But that's not really true. This is
 enough to launch a default window from the console:
 
from Tkinter import *
foo = Tk()

Depends on the platform if this shows a window.

 Do I use Tk() or toplevel()? (Support for both and if a cogent
 explanation of the differences exists, I didn't find it.)

`Tk` is the main window, `Toplevel` for additional windows.  Don't create
several `Tk` instances.  That usually causes very weird side effects.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a question in python curses modules

2008-02-15 Thread Marc 'BlackJack' Rintsch
On Fri, 15 Feb 2008 11:55:11 +0800, Marco wrote:

 Hi, I wanna write a simple curses program, but somethings confuse
 me, my code here:
 
 #!/usr/bin/python
 
 import os
 import sys
 import time
 import curses
 
 class CursesObject( object ):
 
 def __init__(self):
 
 self.STDSCR = curses.initscr()
 curses.noecho()
 curses.cbreak()
 self.STDSCR.keypad(1)
 
 def __del__(self):
 self.STDSCR.keypad(0)
 curses.nocbreak()
 curses.echo()
 curses.endwin()
 
 c1 = CursesObject()
 time.sleep(1)
 
 
 I donot know what happen, but in __del__ function, curses become None??!!

When the interpreter shuts down it has to remove objects.  Everything you
need in a `__del__()` method must be referenced by that object to be sure
that it is still there and not already garbage collected.  *But* it's not
guaranteed that `__del__()` is called at all!  So if you think this clean
up is necessary to leave a usable console then don't put it into a
`__del__()` method!

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a question in python curses modules

2008-02-15 Thread Marc 'BlackJack' Rintsch
On Fri, 15 Feb 2008 15:10:12 +, Sion Arrowsmith wrote:

 Marc 'BlackJack' Rintsch  [EMAIL PROTECTED] wrote:
When the interpreter shuts down it has to remove objects.  Everything you
need in a `__del__()` method must be referenced by that object to be sure
that it is still there and not already garbage collected.  *But* it's not
guaranteed that `__del__()` is called at all!
 
 This may be true, but it's not really the point here, since clearly
 __del__() *is* being called, otherwise how would the OP know that
 curses was None in it?

It's not the point the OP asked for directly but just the answer in the
first two sentences might have left the impression it's okay to use
`__del__()` for this kind of clean up if you make sure that `curses` is
bound to the object.  Then it may appear to work for the OP but it's not
guaranteed to work under all circumstances.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fromfunc functions

2008-02-13 Thread Marc 'BlackJack' Rintsch
On Wed, 13 Feb 2008 07:51:36 -0800, azrael wrote:

 I came across the fromfunc() function in numpy where you pass as an
 argument the name of a function as a string and also the atributes for
 the desired function.

If you mean `fromfunction()` then you don't give the name of the function
as string but the function itself as argument.  And what you call
attributes are arguments.

 I find this extremly usefull and sexy. Can someone point me how write
 a function of such capabilities

Functions are objects in Python, you can pass them around like any other
object/value.

In [18]: def f(func, arg):
   : return func(arg)
   :

In [19]: f(int, '42')
Out[19]: 42

In [20]: f(str.split, 'a b c')
Out[20]: ['a', 'b', 'c']

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ways to declare empty set variable

2008-02-12 Thread Marc 'BlackJack' Rintsch
On Tue, 12 Feb 2008 14:45:43 +0100, Sun wrote:

 then the question is how can I declare a empty set variable as a 'var= []' 
 do to a list variable?

You don't declare variables in Python.  Just create an instance of `set`
and bind it to a name:

var = set()

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __builtins__

2008-02-08 Thread Marc 'BlackJack' Rintsch
On Fri, 08 Feb 2008 00:25:14 -0800, loquehumaine wrote:

 I have seen that if I type help() at a prompt, and then 'modules',
 I'll be given a list of all modules available, thanks to this group..
 But I have seen the differences between them and the one in
 dir(__builtins__).
 Why are some modules in __builtins__ and others don't ? (UserDict for
 example)

`__builtins__` doesn't contain modules::

 Python 2.4.4 (#2, Apr 12 2007, 21:03:11)
 [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
 Type help, copyright, credits or license for more information.
  import inspect
  inspect.getmembers(__builtins__, inspect.ismodule)
 []

 Why dir(__builtins__) gives me math but not help(__builtins__) ?

So there's no 'math' in `__builtins__`::

  'math' in dir(__builtins__)
 False

 What are the differences between __builtins__ and __builtin__ ? (By
 the way, I have python 2.4)

`__builtins__` is an implementation detail, and `__builtin__` is a name
of a module you can import.  You should not use `__builtins__` but import
`__builtin__` and inspect that instead of `__builtins__`.

The (symmetric) difference of the two is empty::

  import __builtin__
  set(dir(__builtins__)).symmetric_difference(dir(__builtin__))
 set([])

 Finally, if I do del(__builtins__), what can I do to repair the
 mistake (as I got an import error __import__ not found if I want to
 import __builtins__...?

Don't ``del __builtins__`` in the first place.  :-)

 That's may be obvious for you, but that's all strange to me and I
 didn't find answers on the net...

So the real question is, why you see 'math' in `__builtins__`.  It should
not be there.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why not a Python compiler?

2008-02-08 Thread Marc 'BlackJack' Rintsch
On Fri, 08 Feb 2008 17:45:36 +, Grant Edwards wrote:

 On 2008-02-08, Arnaud Delobelle [EMAIL PROTECTED] wrote:
 
 Please get back on topic.  This discussion is about parsecs and
 wookies now.
 
 What's a wookie a unit of?

The degree of confusion among the jury when using the Chewbacca defense. :-)

http://en.wikipedia.org/wiki/Chewbacca_defense

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why not a Python compiler?

2008-02-08 Thread Marc 'BlackJack' Rintsch
On Fri, 08 Feb 2008 05:12:29 -0800, Ryszard Szopa wrote:

 Expressing simple loops as C for loops...

You mean simple loops like ``for i in xrange(1000):``?  How should the
compiler know what object is bound to the name `xrange` when that loop is
executed?

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: beginner question, function returning object.

2008-02-07 Thread Marc 'BlackJack' Rintsch
On Thu, 07 Feb 2008 19:14:54 +1100, bambam wrote:

 I started with ths:
  --
 def open_pipe():
 pipe=PIPE()
 print pipe
 return pipe
 
  pipe=open_pipe()
 pipe.parent = self.parent
 print pipe
  --
  It didn't do what I wanted: when I printed the pipe the second time it was
  not the same object as the first time.

Please post actual minimal code that reproduces the problem and a better
description of what you get and what you expected instead.

What is `PIPE` and where does `self` come from?  What are the too
``print``\s printing that makes you think `pipe` isn't bound to the same
object?

  So I changed it to this:
 def open_pipe(pipe):
 pipe=PIPE()
 print pipe
 
  pipe = None
 open_pipe(pipe)
 pipe.parent = self.parent
 print pipe
 
  It still doesn't do what I wanted: I can't assign the parent property
  because pipe type is None.

Yes because in `open_pipe()` you bind a new object to the local name
`pipe` which of course has no effect on the binding of the name `pipe` in
the callers namespace.

 I'm not sure enough of what I am doing to tell if I have another error in 
 my code causing the problem. Is either of these examples supposed to work
 as shown? Is it clear that either example is obviously wrong?

The second is wrong.  The first should work if `self` and `PIPE` are bound
to appropriate objects.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getting all user defined attributes of a class

2008-02-06 Thread Marc 'BlackJack' Rintsch
On Wed, 06 Feb 2008 14:07:23 -0800, Amit Gupta wrote:

 Class A(object) :
   self.x = 1

This is not valid Python code.

 I want something like:
   for userattrib in A.getAllUserAttribute() :
 print userattrib
 
 My question is, is there a builtin function, called
 getAllUserAttributes?

No and there can't be since the attributes you seem to be interested in
don't exist until an instance is created.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getting all user defined attributes of a class

2008-02-06 Thread Marc 'BlackJack' Rintsch
On Wed, 06 Feb 2008 15:16:26 -0800, Amit Gupta wrote:

 On Feb 6, 2:55 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote:
 Amit Gupta schrieb:
  I should make class A as:
  class A (object) :
x = 1

  Now, x is class attribute and I am looking for some-way to filter non-
  user-defined attributes.

  e.g.g if I do
  for attr in a.__dict__ :
print attr

  I will also get

  __module__, __weakref__ and others including x

 Just create an empty class, gather all attribute names from that and
 then subtract that set of names from the names you get from a real class.

 Dize
 
 Fine. This is a hack. I am looking if python language itself provides
 any built-in function for this. E.g.:

Why is that a hack!?  What about:

In [369]: def is_special_name(name):
   .: return name.startswith('__') and name.endswith('__')
   .:

In [370]: filter(lambda m: not is_special_name(m[0]), inspect.getmembers(A))
Out[370]: [('x', 1)]

 When I do help on some built-in function, it displays that function is
 built_in. Can that information get accessed using a function? (now,
 don't ask me to store help-output in buffer and grep for built-in).

Yes but it is not built-in.  Have a look at the `inspect` module.

What's the use case?

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Elementary string-parsing

2008-02-05 Thread Marc 'BlackJack' Rintsch
On Tue, 05 Feb 2008 06:19:12 +, Odysseus wrote:

 In article [EMAIL PROTECTED],
  Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote:
 
 Another issue is testing.  If you rely on global names it's harder to test
 individual functions. [...]
 
 In programs without such global names you see quite clearly in the
 ``def`` line what the function expects as input.
 
 Good points, although thorough commenting can go a long way to help on 
 both counts. In theory, at least ...

Won't work in practice so well.  Say we have function `f()` and
document that it expects global name `a` to be set to something before
calling it. `f()` is used by other functions so we have to document `a` in
all other functions too.  If we change `f()` to rely on global name `b`
too we have to hunt down every function that calls `f()` and add the
documentation for `b` there too.  It's much work and error prone.  Easy to
get inconsistent or missing documentation this way.

To write or check documentation for a function you have to scan the whole
function body for data in global names and calls to other functions and
repeat the search there.  If you don't let functions communicate via global
names you just have to look at the argument list to see the input sources.

 def main():
 # Main program comes here.
 
 if __name__ == '__main__':
 main()
 
 Then main is called when the script is called as program, but not called if
 you just import the script as module.  For example to test functions or to
 reuse the code from other scripts.
 
 I'm using if __name__ == 'main' now, but only for test inputs (which 
 will eventually be read from a config file or passed by the calling 
 script -- or something). I hadn't thought of putting code that actually 
 does something there. As for writing modules, that's way beyond where I 
 want to go at this point: I don't know any C and am not sure I would 
 want to ...

What does this have to do with C!?  There's no specific C knowledge
involved here.

  assert name.startswith('Name: ')
 
 It checks if `name` really starts with 'Name: '.  This way I turned the
 comment into code that checks the assertion in the comment.
 
 Good idea to check, although this is actually only one of many 
 assumptions I make about the data -- but what happens if the assertion 
 fails? The program stops and the interpreter reports an AssertionError 
 on line whatever?

Yes, you get an `AssertionError`:

In [314]: assert True

In [315]: assert False
---
type 'exceptions.AssertionError'Traceback (most recent call last)

/home/bj/ipython console in module()

type 'exceptions.AssertionError':

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Elementary string-parsing

2008-02-04 Thread Marc 'BlackJack' Rintsch
On Mon, 04 Feb 2008 09:43:04 +, Odysseus wrote:

 In article [EMAIL PROTECTED],
  Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote:
 
 def extract_data(names, na, cells):
 found = dict()
 
 The problem with initializing the 'super-dictionary' within this 
 function is that I want to be able to add to it in further passes, with 
 a new set of names  cells each time.

Then you can either pass in `found` as argument instead of creating it
here, or you collect the passes in the calling code with the `update()`
method of `dict`.  Something like this:

found = dict()
for pass in passes:
# ...
found.update(extract_data(names, na, cells))

 BTW what's the difference between the above and found = {}?

I find it more explicit.  ``dict`` and ``list`` are easier to
distinguish than ``{}`` and ``[]`` after a lng coding session or when
printed/displayed in a small font.  It's just a matter of taste.

 for i, name in enumerate(names):
 data = dict()
 cells_index = 10 * i + na
 for cell_name, index, parse in (('epoch1', 0, parse_date),
 ('epoch2', 1, parse_date),
 ('time', 5, parse_number),
 ('score1', 6, parse_number),
 ('score2', 7, parse_number)):
 data[cell_name] = parse(cells[cells_index + index])
 
 This looks a lot more efficient than my version, but what about the 
 strings that don't need parsing? Would it be better to define a 
 'pass-through' function that just returns its input, so they can be 
 handled by the same loop, or to handle them separately with another loop?

I'd handle them in the same loop.  A pass-through function for strings
already exists:

In [255]: str('hello')
Out[255]: 'hello'

 assert name.startswith('Name: ')
 
 I looked up assert, but all I could find relates to debugging. Not 
 that I think debugging is something I can do without ;) but I don't 
 understand what this line does.

It checks if `name` really starts with 'Name: '.  This way I turned the
comment into code that checks the assertion in the comment.

 The `parse_number()` function could look like this:
 
 def parse_number(string):
 try:
 return float(string.replace(',', ''))
 except ValueError:
 return string
 
 Indeed the commas can be replaced a bit more elegant.  :-)
 
 Nice, but I'm somewhat intimidated by the whole concept of 
 exception-handling (among others). How do you know to expect a 
 ValueError if the string isn't a representation of a number?

Experience.  I just tried what happens if I feed `float()` with a string
that is no number:

In [256]: float('abc')
---
type 'exceptions.ValueError'Traceback (most recent call last)

/home/bj/ipython console in module()

type 'exceptions.ValueError': invalid literal for float(): abc

 Is there a list of common exceptions somewhere? (Searching for
 ValueError turned up hundreds of passing mentions, but I couldn't find
 a definition or explanation.)

The definition is quite vague.  The type of an argument is correct, but
there's something wrong with the value.

See http://docs.python.org/lib/module-exceptions.html for an overview of
the built in exceptions.

 As already said, that ``while`` loop should be a ``for`` loop.  But if
 you put `m_abbrevs` into a `list` you can replace the loop with a
 single call to its `index()` method: ``dlist[1] =
 m_abbrevs.index(dlist[1]) + 1``.
 
 I had gathered that lists shouldn't be used for storing constants. Is
 that more of a suggestion than a rule?

Some suggest this.  Others say tuples are for data where the position of
an element has a meaning and lists are for elements that all have the
same meaning for some definition of meaning.  As an example ('John',
'Doe', 'Dr.') vs. ['Peter', 'Paul', 'Mary'].  In the first example we have
name, surname, title and in the second example all elements are just
names.  Unless the second example models a relation like child, father,
mother, or something like that.  Anyway, if you can make the source simpler
and easier to understand by using the `index()` method, use a list.  :-)

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unexpected timing results with file I/O

2008-02-04 Thread Marc 'BlackJack' Rintsch
On Mon, 04 Feb 2008 10:48:32 -0800, rdahlstrom wrote:

 It doesn't matter how many doors opening and closing there are, it
 matters the order in which the opening, walking through, and closing
 are done.  That's my point.  In the second example, all of the disk
 operations are done at the same time.  That's what I meant by people
 going through the doors.  Maybe it was more clear in my head.

But my timing shows that method two is slower on my computer.  So there is
no obvious winner.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unexpected timing results with file I/O

2008-02-04 Thread Marc 'BlackJack' Rintsch
On Mon, 04 Feb 2008 15:17:18 +, Steven D'Aprano wrote:

 # Method one: grouped by file.
 for each file:
 open the file, append the string, then close it
 
 
 # Method two: grouped by procedure.
 for each file:
 open the file
 for each open file:
 append the string
 for each open file:
 close the file

 Method 1:
 
 17.391216039657593
 
 Method 2:
 
 16.823362112045288
 
 
 Surprisingly, Method 2 is a smidgen faster, by about half a second over 
 500,000 open-write-close cycles. It's not much faster, but it's 
 consistent, over many tests, changing many of the parameters (e.g. the 
 number of files, the number of runs per timeit test, etc.).
 
 I'm using Linux and Python 2.5.
 
 So, what's going on? Can anyone explain why the code which does more work 
 takes less time?

Can't confirm this (Linux, Python 2.5):

Method 1: 15.380897998809814
Method 2: 18.085366010665894

I guess it's really all about the disk IO as my system monitor applet
shows that almost all of the time is spend in the kernel and very little
in user space.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Elementary string-parsing

2008-02-04 Thread Marc 'BlackJack' Rintsch
On Mon, 04 Feb 2008 12:25:24 +, Odysseus wrote:

 I'm not clear on what makes an object global, other than appearing as an 
 operand of a global statement, which I don't use anywhere. But na is 
 assigned its value in the program body, not within any function: does 
 that make it global?

Yes.  The term global usually means module global in Python.

 Why is this not recommended?

Because the functions depend on some magic data coming from nowhere and
it's much harder to follow the data flow in a program.  If you work with
globals you can't be sure what the following will print:

def spam():
global x
x = 42
beep()
print x

`beep()` might change `x` or any function called by `beep()` and so on. 

Another issue is testing.  If you rely on global names it's harder to test
individual functions.  If I want to test your `extract_data()` I first have
to look through the whole function body and search all the global
references and bind those names to values before I can call the function. 
This might not be enough, any function called by `extract_data()` might
need some global assignments too.  This way you'll get quite soon to a
point where the single parts of a program can't be tested in isolation and
are not reusable for other programs.

In programs without such global names you see quite clearly in the
``def`` line what the function expects as input.

 If I wrap the assignment in a function, making na a local variable, how
 can extract_data then access it?

Give it as an argument.  As a rule of thumb values should enter a function
as arguments and leave it as return values.

It's easy to enforce if you have minimal code on the module level.  The
usual idiom is:

def main():
# Main program comes here.

if __name__ == '__main__':
main()

Then main is called when the script is called as program, but not called if
you just import the script as module.  For example to test functions or to
reuse the code from other scripts.

 def extract_data(names, na, cells):
 
  and
 
  return something
 
 What should it return? A Boolean indicating success or failure? All the
 data I want should all have been stored in the found dictionary by the
 time the function finishes traversing the list of names.

Then create the `found` dictionary in that function and return it at the
end.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unexpected timing results with file I/O

2008-02-04 Thread Marc 'BlackJack' Rintsch
On Mon, 04 Feb 2008 10:18:39 -0800, rdahlstrom wrote:

 On Feb 4, 1:12 pm, Carl Banks [EMAIL PROTECTED] wrote:
 On Feb 4, 12:53 pm, rdahlstrom [EMAIL PROTECTED] wrote:
  You have 500,000 people to fit through a door.  Here are your options:

  1.  For each person, open the door, walk through the door, then close
  the door.
  2.  Open the door, allow everyone to walk through, then close the
  door.

  Which one would you say would be a more efficient way to fit 500,000
  people through the door?

 Bad analogy.  A better analogy would be if each person has their own
 door to walk through.

 The analogy holds.  It's faster to open the door, do what you need to
 do, then close the door than it is to open and close the door each
 time.

It doesn't hold.  Read the code again.  The total count of open door and
close door is the same in both cases.

It's

  for every person:
  open his door; push him through the door; close his door

vs.

  for every person:
  open his door
  for every person:
  push him through the door
  for every person:
  close his door

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: future multi-threading for-loops

2008-02-04 Thread Marc 'BlackJack' Rintsch
On Mon, 04 Feb 2008 19:22:29 -0800, castironpi wrote:

 Some iterables and control loops can be multithreaded.  Worries that
 it takes a syntax change.
 
 for X in A:
 def f( x ):
 normal suite( x )
 start_new_thread( target= f, args= ( X, ) )
 
 Perhaps a control-flow wrapper, or method on iterable.
 
 @parallel
 for X in A:
 normal suite( X )
 
 for X in parallel( A ):
 normal suite( X )
 
 Discussion presued about multi-core systems.  Allow user certain
 control over what runs on multi-core.  Clearly, not generally
 applicable.  -- But, from __future__ import does change syntax.

Why not simply writing a function?

def execute_parallel(f, A):
for args in A:
start_new_thread(target=f, args=args)


def f(x):
normal_suit(x)

parallel(f, A)

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: extending python with array functions

2008-02-04 Thread Marc 'BlackJack' Rintsch
On Mon, 04 Feb 2008 20:56:02 -0200, Gabriel Genellina wrote:

 - the array module http://docs.python.org/lib/module-array.html provides  
 homogeneuos arrays that may be more efficient for your application. arrays  
 don't have a special API, you have to import the module and use its  
 functions the same as one would do in pure Python.

There's one special thing about it: the `buffer_info()` method returns a
tuple with the memory address and length (in items) of the current
underlying buffer. Pretty useless information in Python but handy in
extensions that can directly access the raw memory.

To the OP:  Since Python 2.5 the `ctypes` module is another way to
interface with native code in dynamic libraries from the standard
library.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Unexpected timing results with file I/O

2008-02-04 Thread Marc 'BlackJack' Rintsch
On Mon, 04 Feb 2008 21:58:46 +, Steven D'Aprano wrote:

 On Mon, 04 Feb 2008 17:08:02 +, Marc 'BlackJack' Rintsch wrote:
 
 Surprisingly, Method 2 is a smidgen faster, by about half a second over
 500,000 open-write-close cycles. It's not much faster, but it's
 consistent, over many tests, changing many of the parameters (e.g. the
 number of files, the number of runs per timeit test, etc.).
 
 I'm using Linux and Python 2.5.
 
 So, what's going on? Can anyone explain why the code which does more
 work takes less time?
 
 Can't confirm this (Linux, Python 2.5):
 
 Method 1: 15.380897998809814
 Method 2: 18.085366010665894
 
 Hmmm... does your system use software RAID? Mine does. I wonder if that's 
 a relevant factor?

No, test ran on a plain reiserfs partition.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Elementary string-parsing

2008-02-04 Thread Marc 'BlackJack' Rintsch
On Mon, 04 Feb 2008 03:21:18 +, Odysseus wrote:

 def extract_data():
 i = 0
 while i  len(names):
 name = names[i][6:] # strip off Name: 
 found[name] = {'epoch1': cells[10 * i + na],
'epoch2': cells[10 * i + na + 1],
'time': cells[10 * i + na + 5],
'score1': cells[10 * i + na + 6],
'score2': cells[10 * i + na + 7]}

Here and in later code you use a ``while`` loop although it is known at
loop start how many times the loop body will be executed.  That's a job
for a ``for`` loop.  If possible not over an integer that is used later
just as index into list, but the list itself.  Here you need both, index
and objects from `names`.  There's the `enumerate()` function for creating
an iterable of (index, name) from `names`.

I'd put all the relevant information that describes a field of the
dictionary that is put into `found` into tuples and loop over it.  There
is the cell name, the index of the cell and function that converts the
string from that cell into an object that is stored in the dictionary. 
This leads to (untestet):

def extract_data(names, na, cells):
found = dict()
for i, name in enumerate(names):
data = dict()
cells_index = 10 * i + na
for cell_name, index, parse in (('epoch1', 0, parse_date),
('epoch2', 1, parse_date),
('time', 5, parse_number),
('score1', 6, parse_number),
('score2', 7, parse_number)):
data[cell_name] = parse(cells[cells_index + index])
assert name.startswith('Name: ')
found[name[6:]] = data
return found

The `parse_number()` function could look like this:

def parse_number(string):
try:
return float(string.replace(',', ''))
except ValueError:
return string

Indeed the commas can be replaced a bit more elegant.  :-)

`parse_date()` is left as an exercise for the reader.

 for k in ('epoch1', 'epoch2'):
 dlist = found[name][k].split( )
 m = 0
 while m  12:
 if m_abbrevs[m] == dlist[1]:
 dlist[1] = m + 1
 break
 m += 1
 tlist = dlist[3].split(:)
 found[name][k] = timegm((int(dlist[2]), int(dlist[1]),
  int(dlist[0]), int(tlist[0]),
  int(tlist[1]), int(tlist[2]),
  -1, -1, 0))
 i += 1
 
 The function appears to be working OK as is, but I would welcome any  
 all suggestions for improving it or making it more idiomatic.

As already said, that ``while`` loop should be a ``for`` loop.  But if you
put `m_abbrevs` into a `list` you can replace the loop with a single call
to its `index()` method: ``dlist[1] = m_abbrevs.index(dlist[1]) + 1``.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: psyco question

2008-02-03 Thread Marc 'BlackJack' Rintsch
On Sun, 03 Feb 2008 10:06:04 -0800, miller.paul.w wrote:

 Say I have a module with a function f in it, and I do
 
 psyco.bind (f)
 
 Is there any simple/easy/elegant way to retain a reference to the
 *unoptimized* version of f so I can call them both and compare
 performance?

What about `psyco.unbind()`?

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Does anyone else use this little idiom?

2008-02-03 Thread Marc 'BlackJack' Rintsch
On Sun, 03 Feb 2008 15:13:14 +1100, Ben Finney wrote:

 Gabriel Genellina [EMAIL PROTECTED] writes:
 
 Should be `for _ in xrange(n)` to match the Ruby example. Both
 iterate n times.
 
 Only until Python 3.0, since the 'xrange' implementation will become
 'range' at that time.

The point wasn't `range` vs. `xrange` but the arguments (1,n) vs. (n).

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Does anyone else use this little idiom?

2008-02-03 Thread Marc 'BlackJack' Rintsch
On Sun, 03 Feb 2008 05:33:16 -0800, Ivan Illarionov wrote:

 Plain Python function are very often more powerful than classes:
 
 def go(count):
 ...   if not hasattr(go, 'count'):
 ... go.count = count
 ...   if go.count = 0:
 ... del go.count
 ... return False
 ...   go.count -= 1
 ...   return True
 ...
 while go(3):
 ...   print 'hello'
 ...
 hello
 hello
 hello


Please try:

while go(3):
while go(3):
print 'Think about it...'

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unicode literals to latin-1

2008-01-30 Thread Marc 'BlackJack' Rintsch
On Wed, 30 Jan 2008 09:57:55 +0100, David.Reksten wrote:

 How can I convert a string read from a database containing unicode
 literals, such as Fr\u00f8ya to the latin-1 equivalent, Frøya?
 
 I have tried variations around
   Fr\u00f8ya.decode('latin-1')
 but to no avail.

In [388]: 'Fr\u00f8ya'.decode('unicode-escape')
Out[388]: u'Fr\xf8ya'

In [389]: print 'Fr\u00f8ya'.decode('unicode-escape')
Frøya

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Removing Pubic Hair Methods

2008-01-30 Thread Marc 'BlackJack' Rintsch
On Tue, 29 Jan 2008 11:48:38 -0800, Tobiah wrote:

 class genital:
 
   def pubic_hair(self):
   pass
 
   def remove(self):
   del(self.pubic_hair)

I think `pubic_hair` is an attribute instead of a method.

Oh, and ``del`` is a statement and not a function.  So the way you wrote
it with parentheses is a bit misleading.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Removing Pubic Hair Methods

2008-01-30 Thread Marc 'BlackJack' Rintsch
On Wed, 30 Jan 2008 15:29:45 +0100, Wildemar Wildenburger wrote:

 Gerardo Herzig wrote:
 I will use genital().extend(), thats for shure ^^
 
 Well, you never go wrong with apply(genital(), females), do you?

`apply()` is deprecated.  And ``genital(*females)`` looks a bit odd.  :-)

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary Keys question

2008-01-30 Thread Marc 'BlackJack' Rintsch
On Wed, 30 Jan 2008 17:19:13 -0800, Ryszard Szopa wrote:

 BTW, can anybody explain me how is the hash function implemented in
 Python?

It calls the `__hash__()` method on the object that was given as argument.
So there's not *the* hash function, but every type implements its own.

Fallback is the hash of the identity of an object:

In [415]: class A(object): pass
   .:

In [416]: a = A()

In [417]: hash(a)
Out[417]: 161029068

In [418]: hash(id(a))
Out[418]: 161029068

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: read and readline hanging

2008-01-28 Thread Marc 'BlackJack' Rintsch
On Sun, 27 Jan 2008 19:58:27 +0100, Olivier Lefevre wrote:

 But how can I find out *programmatically* that there is no more
 input?
 
 You can't.
 
 How do people handle this, then? Reading from a process that will
 block if you ask too much yet won't let you know how much there is
 to read right now has to be some kind of FAQ.

It's impossible to handle if the external process does not tell you
somehow if there's still data ahead or if it is finished.  Then there's
only the closing of the file on the process' side that tells you the
definitive end of the data.

 This doesn't answer if the interpreter doesn't flush its output buffer
 after every line.
 
 I think it must otherwise you might get incomplete answers or no
 answers at the interactive prompt and that never happens. It may
 not flush its buffer after every line but it must flush them at
 the end of an answer.

The buffering behavior at the interactive prompt is very often different
from connections via pipes.  If stdout of a process is connected to a
terminal the standard C library chooses line buffering but if it is
connected to a pipe or redirected to a file it chooses block buffering
instead.

In such cases the `pexpect` module might be a solution.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: optional static typing for Python

2008-01-28 Thread Marc 'BlackJack' Rintsch
On Mon, 28 Jan 2008 08:31:43 -0800, John Nagle wrote:

 Unenforced static typing is somewhat pointless.  If that
 goes in, it should be enforced by implementations.

Luckily we don't get static typing.  We get annotations which *can* be
used for type hints, checked by additional code.  Can be used for other
things as well.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A question about osyco

2008-01-28 Thread Marc 'BlackJack' Rintsch
On Mon, 28 Jan 2008 05:31:41 -0800, iu2 wrote:

 I wrote two version of a fib functions, a recursive one and an
 iterative one.
 Psyco improved a lot the recursive function time, but didn't affect at
 all the iterative function.
 
 Why?

Try calling the iterative one twice and measure the time of the second
call.  IIRC psyco needs at least one call to analyze the function, so the
first call is not speed up.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to make format operator % work with unicode as expected

2008-01-27 Thread Marc 'BlackJack' Rintsch
On Sun, 27 Jan 2008 05:32:40 +, Peter Pei wrote:

 You didn't understand my question, but thanks any way.
 
 Yes, it is true that %s already support unicode, and I did not contradict 
 that. But it counts the number of bytes instead of characters, and makes 
 things like %-20s out of alignment. If you don't understand my assertion, 
 please don't argue back and I am only interested in answers from those who 
 are qualified.

I have the impression from your original post

  […] because it is unicode, and one byte is not neccessary one character.

that you confuse unicode and utf-8.  Are you sure you are qualified to ask
such a question in the first place!?  :-þ

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Sorting Large File (Code/Performance)

2008-01-27 Thread Marc 'BlackJack' Rintsch
On Sun, 27 Jan 2008 10:00:45 +, Grant Edwards wrote:

 On 2008-01-27, Stefan Behnel [EMAIL PROTECTED] wrote:
 Gabriel Genellina wrote:
 use the Windows sort command. It has been
 there since MS-DOS ages, there is no need to download and install other
 packages, and the documentation at
 http://technet.microsoft.com/en-us/library/bb491004.aspx says:
 
 Limits on file size:
   The sort command has no limit on file size.

 Sure, since no-one can ever try it with more than 640k, it's
 easy to state that there is no limit. :)
 
 Huh?  I used DOS sort to sort files much bigger than 640K.

That was an allusion to a quote misattributed to Bill Gates about DOS:

  640K ought to be enough for anybody.

http://en.wikiquote.org/wiki/Bill_Gates#Misattributed

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Some questions about decode/encode

2008-01-27 Thread Marc 'BlackJack' Rintsch
On Sun, 27 Jan 2008 02:18:48 -0800, glacier wrote:

 Yepp. I feed SAX with the unicode string since SAX didn't support my
 encoding system(GBK).

If the `decode()` method supports it, IMHO SAX should too.

 Is there any way to solve this better?
 I mean if I shouldn't convert the GBK string to unicode string, what
 should I do to make SAX work?

Decode it and then encode it to utf-8 before feeding it to the parser.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: translating Python to Assembler

2008-01-27 Thread Marc 'BlackJack' Rintsch
On Sun, 27 Jan 2008 10:55:20 +, over wrote:

 On Sat, 26 Jan 2008 14:47:50 +0100, Bjoern Schliessmann
 [EMAIL PROTECTED] wrote:
 
 The script is essentially gone. I'd like to know how to read the pyc
 files, but that's getting away from my point that there is a link
 between python scripts and assembler. At this point, I admit the code
 above is NOT assembler, but sooner or later it will be converted to
 machine code by the interpreter and the OS and that can be
 disassembled as assembler.  

No it will not be converted to assembler.  The byte code is *interpreted*
by Python, not compiled to assembler.  If you want to know how this
happens get the C source code of the interpreter and don't waste your time
with disassembling `python.exe`.  C is much easier to read and there are
useful comments too.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: translating Python to Assembler

2008-01-27 Thread Marc 'BlackJack' Rintsch
On Sun, 27 Jan 2008 11:23:20 +, over wrote:

 Don't fucking tell me about assembler, you asshole. I can read
 disassembled code in my sleep.

Yes you can read it, but obviously you don't understand it.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: translating Python to Assembler

2008-01-27 Thread Marc 'BlackJack' Rintsch
On Sun, 27 Jan 2008 13:41:54 +, Steven D'Aprano wrote:

 On Sun, 27 Jan 2008 10:55:20 +, over wrote:
 
 I can understand people thinking I'm full of beans.
 
 Oh no, not full of beans. Full of something, but not beans.
 
 Everything you have written about assembly, machine code, compilers, 
 Linux, Python and so forth has been a confused mish-mash of half-truths, 
 distortions, vaguely correct factoids and complete nonsense.
 
 I'm starting to wonder if it is possible for somebody to be 
 simultaneously so self-assured and so ignorant, or if we're being trolled.

I recently learned that this is called the Dunning-Kruger effect:

  The Dunning-Kruger effect is the phenomenon wherein people who have
  little knowledge think that they know more than others who have much
  more knowledge.

  […]

  The phenomenon was demonstrated in a series of experiments performed by
  Justin Kruger and David Dunning, then both of Cornell University. Their
  results were published in the Journal of Personality and Social
  Psychology in December 1999.

  http://en.wikipedia.org/wiki/Dunning-Kruger_effect

See, there's almost always a rational explanation.  ;-)

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: how to make format operator % work with unicode as expected

2008-01-27 Thread Marc 'BlackJack' Rintsch
On Sun, 27 Jan 2008 16:00:42 +, Peter Pei wrote:

 Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote in message 
 news:[EMAIL PROTECTED]
 On Sun, 27 Jan 2008 05:32:40 +, Peter Pei wrote:

 You didn't understand my question, but thanks any way.

 Yes, it is true that %s already support unicode, and I did not contradict
 that. But it counts the number of bytes instead of characters, and makes
 things like %-20s out of alignment. If you don't understand my assertion,
 please don't argue back and I am only interested in answers from those 
 who are qualified.

 I have the impression from your original post

  […] because it is unicode, and one byte is not neccessary one character.

 that you confuse unicode and utf-8.  Are you sure you are qualified to
 ask such a question in the first place!?  :-þ
 so you are saying, with utf-8 encoding a byte is a character, shame on
 you.

No I don't say that.  I say unicode has no bytes but codepoints.  And with
unicode objects Python counts characters and not bytes.  So I guess you
are trying to format utf-8 encoded byte strings instead of unicode
strings.  Because with unicode strings your problem simply does not
exist.  As several people already *showed* to you with examples.  Once
again:

In [346]: u = u'sm\xf8rebr\xf8d'

In [347]: s = u.encode('utf-8')

In [348]: print '%-20s+\n%-20s+' % (s, 'spam')
smørebrød +
spam+

In [349]: print '%-20s+\n%-20s+' % (u, 'spam')
smørebrød   +
spam+

348 is what you are doing, utf-8 encoded byte strings, but you claim that's
a problem with unicode.

And 349 is formatting unicode.  See, no problem -- lines up nicely.

Instead of embarrassing yourself and being rude to people you should take
some time and learn something about unicode and encodings.  Especially that
utf-8 ≠ unicode.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: translating Python to Assembler

2008-01-26 Thread Marc 'BlackJack' Rintsch
On Sat, 26 Jan 2008 03:09:05 +, Steven D'Aprano wrote:

 On Wed, 23 Jan 2008 08:49:20 +0100, Christian Heimes wrote:
 
 It's even
 possible to write code with Python assembly and compile the Python
 assembly into byte code.
 
 Really? How do you do that?
 
 I thought it might be compile(), but apparently not.

Maybe `bytecodehacks`_ + `psyco`, or PyPy!?

.. _bytecodehacks: http://sourceforge.net/projects/bytecodehacks/

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: When is min(a, b) != min(b, a)?

2008-01-25 Thread Marc 'BlackJack' Rintsch
On Fri, 25 Jan 2008 07:57:38 +, Pete Forman wrote:

 Mark Dickinson [EMAIL PROTECTED] writes:
 
   Any change to Python that made == and != checks involving NaNs raise
   an exception would have to consider the consequences for set, dict,
   list membership testing.
   […]
   and if Python had separate operators for these two purposes it
   wouldn't be Python any more.
 
 There are separate Python operators, == and is.

So what?  ``==`` is used for both ``==`` and set/dict/list membership
testing and nested comparison of those structures.  There is no ``is``
involved.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: read and readline hanging

2008-01-25 Thread Marc 'BlackJack' Rintsch
On Fri, 25 Jan 2008 17:31:16 +0100, Olivier Lefevre wrote:

 Thanks for the answer. Yes this is tricky. I have done it in Java
 before, where you can, e.g., set up a thread to pump stuff out of
 both stderr and stdout continuously but my python is too rudimentary
 for that.

The `trheading` module is modeled after Java's threading API.

 There is a key difference anyway: in Java you can write
 
  while (br.readLine() != null) { pump }
 
 where br is the buffered reader in which you've wrapped the stdout
 of the child process and it will not hang. But in python eventually
 stdout.readline() hangs. This is a real nuisance: why can't it just
 return None?

Because that would be quite annoying because most of the time people want
blocking behavior.

 1. The subprocess has stopped producing output.
 
 Indeed, if I do this interactively, I can tell after 3 lines that I've
 gotten all there is to get right now and the fourth readline() call
 hangs. But how can I find out *programmatically* that there is no more
 input?

You can't.

 If you are only reading its standard output, are you sure that the 
   subprocess is flushing its buffers so you can recognize it's time to
   provide more input?
 
 The subprocess in a purely passive position: it is an interpreter: I
 send it commands and I read the answers. The python side is in charge.

This doesn't answer if the interpreter doesn't flush its output buffer
after every line.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is possible to get order of keyword parameters ?

2008-01-25 Thread Marc 'BlackJack' Rintsch
On Fri, 25 Jan 2008 05:49:40 -0800, rndblnch wrote:

 def f(**kwargs):
 skipped
 return result
 
 such as :
 f(x=12, y=24) == ['x', 'y']
 f(y=24, x=12) == ['y', 'x']
 
 what i need is to get the order of the keyword parameters inside the
 function.
 any hints ?

Impossible.  Dictionaries are unordered.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Some questions about decode/encode

2008-01-24 Thread Marc 'BlackJack' Rintsch
On Wed, 23 Jan 2008 19:49:01 -0800, glacier wrote:

 My second question is: is there any one who has tested very long mbcs
 decode? I tried to decode a long(20+MB) xml yesterday, which turns out
 to be very strange and cause SAX fail to parse the decoded string.

That's because SAX wants bytes, not a decoded string.  Don't decode it
yourself.

 However, I use another text editor to convert the file to utf-8 and
 SAX will parse the content successfully.

Because now you feed SAX with bytes instead of a unicode string.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: piping into a python script

2008-01-24 Thread Marc 'BlackJack' Rintsch
On Thu, 24 Jan 2008 17:17:25 +0200, Donn Ingle wrote:

 Given these two examples:
 1. 
 ./fui.py *.py
 2.
 ls *.py | ./fui.py
 
 How can I capture a list of the arguments?
 I need to get all the strings (file or dir names) passed via the normal
 command line and any that may come from a pipe.
 
 There is a third case:
 3.
 ls *.jpg | ./fui.py *.png
 Where I would be gathering strings from two places.
 
 I am trying to write a command-line friendly tool that can be used in
 traditional gnu/linux ways, otherwise I'd skip the pipe stuff totally.
 
 I have tried:
 1. pipedIn = sys.stdin.readlines()
 Works fine for example 2, but example 1 goes into a 'wait for input' mode
 and that's no good. Is there a way to tell when no input is coming from a
 pipe at all?

Usually Linux tools that can get the data from command line or files treat
a single - as file name special with the meaning of: read from stdin.

So the interface if `fui.py` would be:

1. ./fui.py *.a
2. ls *.a | ./fui.py -
3. ls *.a | ./fui.py *.b -

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Module/package hierarchy and its separation from file structure

2008-01-23 Thread Marc 'BlackJack' Rintsch
On Wed, 23 Jan 2008 03:49:56 -0600, Peter Schuller wrote:

 Let me just shoot down one possible suggestion right away, to show you
 what I am trying to accomplish:
 
 I do *not* want to simply break out X into org.lib.animal.x, and have
 org.lib.animal import org.lib.animal.x.X as X.

Then you shoot down the idiomatic answer I guess.  That's what most people
do.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Stripping whitespace

2008-01-23 Thread Marc 'BlackJack' Rintsch
On Wed, 23 Jan 2008 10:50:02 -0800, ryan k wrote:

 Hello. I have a string like 'LNAME
 PASTA   ZONE'. I want to create a list of those words and
 basically replace all the whitespace between them with one space so i
 could just do lala.split(). Thank you!

You *can* just do ``lala.split()``:

In [97]: lala = 'LNAME   PASTA   ZONE'

In [98]: lala.split()
Out[98]: ['LNAME', 'PASTA', 'ZONE']

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what's this instance?

2008-01-22 Thread Marc 'BlackJack' Rintsch
On Tue, 22 Jan 2008 15:36:49 +0800, J. Peng wrote:

 def safe_float(object):
   try:
 retval = float(object)
   except (ValueError, TypeError), oops:
 retval = str(oops)
   return retval
 
 x=safe_float([1,2,3,4])
 print x
 
 
 The code above works well.But what's the instance of oops? where is it
 coming from? I'm totally confused on it.thanks.

`oops` is bound to the `ValueError` or `TypError` object if `float()`
raises such an exception.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question on sort() key function

2008-01-22 Thread Marc 'BlackJack' Rintsch
On Tue, 22 Jan 2008 09:56:55 +, Robert Latest wrote:

 Peter Otten wrote:
 Robert Latest wrote:

 This should work then:

 def date_key(f):
 return f.mod_date.toordinal()
 flist.sort(key=date_key)

 This can also be written as

 flist.sort(key=lambda f: f.mod_date.toordinal())
 
 Well, that's almost Paul's (non-working) suggestion above, but it works 
 because of the parentheses after toordinal. Beats me how both versions can 
 be valid, anyway.
 
 To me it's all greek. I grew up with C function pointers, and they 
 always work.
 
 robert

Suppose `func` is a C function pointer, then

  foo = func;

and

  foo = func();

have different meanings.  It's just the same in Python.  First is the
function itself, second *calls* the function.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with 'global'

2008-01-21 Thread Marc 'BlackJack' Rintsch
On Mon, 21 Jan 2008 17:08:46 -0200, Gabriel Genellina wrote:

 The future statement is another example, even worse:
 
 if 0:
  from __future__ import with_statement
 
 with open(xxx) as f:
  print f

In Python =2.5 it's a compile time error if that import is not the very
first statement in a source file.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: XOR encryption

2008-01-18 Thread Marc 'BlackJack' Rintsch
On Fri, 18 Jan 2008 03:06:51 -0800, joe jacob wrote:

 I wrote a python script to perform XOR encryption on a text and write
 the encrypted text to a file. But when I try to read the file as the
 encrypted text contains an EOF in between the file is read only to the
 first EOF and remaining part of the text is not read.

You have to open the file in binary mode ('rb'/'wb') instead of text mode
('r'/'w') to stop Windows from interpreting the EOF character this way.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: super, decorators and gettattribute

2008-01-13 Thread Marc 'BlackJack' Rintsch
On Sat, 12 Jan 2008 14:23:52 -0800, Richard Szopa wrote:

 However, I am very surprised to learn that
 
 super_object.__getattr__(name)(*args, **kwargs)
 
 getattr(super_object, name)(*args, **kwargs)
 
 are not equivalent. This is quite odd, at least when with len()
 and .__len__, str() and .__str__. Do you maybe know what's the
 rationale behind not following that convention by getattr?

I think you are confusing `__getattr__` and `__getattribute__` here! 
`getattr()` maps to `__getattr__()`, it's `__getattribute__` that's
different.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: encrypting python modules

2008-01-11 Thread Marc 'BlackJack' Rintsch
On Sat, 12 Jan 2008 09:47:26 +1100, Ben Finney wrote:

 Trying to make bits uncopyable and unmodifiable is like trying to make
 water not wet.

Certainly not.  I can put water into the freezer, but I have no idea how
to make bits uncopyable and unmodifiable while still delivering them to
the clients for execution.  ;-)

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding python code into text document question.

2008-01-10 Thread Marc 'BlackJack' Rintsch
On Thu, 10 Jan 2008 14:10:05 +0100, Thomas Troeger wrote:

 I've written a program that parses a string or file for embedded python 
 commands, executes them and fills in the returned value. The input might 
 look like this:
 
 process id: $$return os.getpid()$$
 current date: $$return time.ctime()$$
 superuser: $$
 if os.geteuid():
   return Yes
 else:
   return No$$
 
 I've tried several solutions using eval, execfile or compile, but none 
 of those would solve my problem. Does anyone have a solution that works? 
 Any suggestions? Any help will be appreciated :)

My suggestion would be:  use one of the many already existing templating
systems.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: adding methods at runtime

2008-01-10 Thread Marc 'BlackJack' Rintsch
On Thu, 10 Jan 2008 14:55:18 -0800, [EMAIL PROTECTED] wrote:

 Can I access the class attributes from a method added at runtime? (My
 experience says no.)
 I experimented with the following code:
 
 [Code snipped]
 
 So it seems to me, if you add a method to an instance, the method will
 not get self as parameter.

You are not adding a method but a function.  Take a look at
`types.MethodType()` to create a method from a function, instance, and
class.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem of converting a list to dict

2008-01-09 Thread Marc 'BlackJack' Rintsch
On Wed, 09 Jan 2008 10:56:36 -0800, Louis.Soninhu wrote:

 Hi pals
 
 I have a list like this
 
 mylist=['','tom=boss','mike=manager','paul=employee','meaningless']
 
 I'd like to remove the first and the last item as they are irrevalent,
 and convert it to the dict:
 {'tom':'boss','mike':'manager','paul':'employee'}
 
 I tried this but it didn't work:
 
 mydict={}
 for i in mylist[1:-1]:
   a=i.split('=')  # this will disect each item of mylist into a 
 2-item
 list
   mydict[a[0]]=a[1]
 
 and I got this:
   File srch, line 19, in module
 grab(a/tags1)
   File srch, line 15, in grab
 mydict[mylist[0]]=mylist[1]
 IndexError: list index out of range
 
 Anyone could shed me a light on this?

The real list you used had at least one string without a '=' in it.  The
list given above doesn't raise that exception:

In [102]: mylist=['','tom=boss','mike=manager','paul=employee','meaningless']

In [103]: mydict={}

In [104]: for i in mylist[1:-1]:
   .: a=i.split('=')
   .: mydict[a[0]]=a[1]
   .:

In [105]: mydict
Out[105]: {'mike': 'manager', 'paul': 'employee', 'tom': 'boss'}

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pet Store

2008-01-08 Thread Marc 'BlackJack' Rintsch
On Mon, 07 Jan 2008 22:21:53 -0800, George Maggessy wrote:

 I'm an experience Java developer trying to learn Python. I just
 finished the Python tutorial on python.org and I'm currently reading
 the Learning Python book. However, if I could find something like a
 simple web app with some best practices, such as those famous Java
 Pet Store apps, I think that would help me to fill up some gaps in my
 learning process. Does anybody know any app like that?

Isn't that a web application using Java web frameworks?  So you are
looking for a Python web framework with a Pet Store tutorial?

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: popen question

2008-01-08 Thread Marc 'BlackJack' Rintsch
On Tue, 08 Jan 2008 09:20:16 +, Robert Latest wrote:

 The program slow just writes the numbers 0 through 9 on stdout, one line a 
 second, and then quits.
 
 I would have expected the python program to spit out a numbers one by one, 
 instead I see nothing for 10 seconds and then the whole output all at once.
 
 How can I get and process the pipe's output at the pace it is generated?

Both processes have to make their communication ends unbuffered or line
buffered.  See the documentation of `os.popen()` for the `bufsize`
argument.  And do whatever is needed to output the numbers from ``slow``
unbuffered or line buffered.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python syntax:urgent

2008-01-08 Thread Marc 'BlackJack' Rintsch
On Tue, 08 Jan 2008 10:03:56 +0100, Jeroen Ruigrok van der Werven wrote:

 -On [20080108 09:42], mpho raborife ([EMAIL PROTECTED]) wrote:
subprocess.Popen([gmmscore, -i, Input, -l, List, -t,
 modeltype, -m, str(mixture), -d, str(dimension), -v, str(vfloor),
 -n, str(number), -r, str(results)])
 
 gmmscore, -i seems a bit silly, why not just gmmscore -i?

That's definitely *not* silly but the way to go.  There are two ways: The
above that calls the executable with the arguments as given, or with a
string like you suggests which is interpreted by a shell, so the arguments
must be escaped for that shell.  Which shell?  Depends on the system!

 You can always do something like (assuming all arguments are strings, adjust
 accordingly):
 
 s = gmmscore -i %s -l %s -t %s -m %s -d %s -v %s -n %s -r %s %
 (Input, List, modeltype, str(mixture), str(dimension), str(vfloor),
  str(number), str(results))
 
 subprocess.Popen([s])

Here you are trying to start a program named gmmscore -i ... with no
arguments.  That fails (unless you really have a program with that name.  ;-)

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Point Object

2008-01-05 Thread Marc 'BlackJack' Rintsch
On Sat, 05 Jan 2008 03:37:33 -0800, [EMAIL PROTECTED] wrote:

 I am nes to python and need some help.  Can anyone lead me in the
 right direction to create and print a Point object, and then use id to
 print the object's unique identifier. Translate the hexadecimal form
 into decimal and confirm that they match.

The right direction would be the tutorial in the docs I guess:

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

What do you mean by the hexadecimal form?  `id()` returns ordinary
`int`\s and not strings.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxpython application ( problem ? )

2008-01-02 Thread Marc 'BlackJack' Rintsch
On Wed, 02 Jan 2008 03:24:56 -0800, vedrandekovic wrote:

 Here is sample of my simple script with wxpython and modules:
 subprocess,threading, directpython...

Are you accessing the GUI from threads?

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pdf library.

2008-01-01 Thread Marc 'BlackJack' Rintsch
On Tue, 01 Jan 2008 04:21:29 -0800, Shriphani wrote:

 On Jan 1, 4:28 pm, Piet van Oostrum [EMAIL PROTECTED] wrote:
 Shriphani[EMAIL PROTECTED] (S) wrote:
 S I tried pyPdf for this and decided to get the pagelinks. The trouble
 S is that I don't know how to determine whether a particular page is the
 S first page of a chapter. Can someone tell me how to do this ?

 AFAIK PDF doesn't have the concept of Chapter. If the document has an
 outline, you could try to use the first level of that hierarchy as the
 chapter starting points. But you don't have a guarantee that they really
 are chapters.

 How would a pdf to html conversion work ? I've seen Google's search
 engine do it loads of times. Just that running a 500odd page ebook
 through one of those scripts might not be such a good idea.

Heuristics?  Neither PDF nor HTML know chapters.  So it might be
guesswork or just in your head.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: at what complexity, a comparison fails ?

2007-12-31 Thread Marc 'BlackJack' Rintsch
On Mon, 31 Dec 2007 11:45:55 +0100, Stef Mientki wrote:

 Now one of the interface mechanisms was to see if some parameter was 
 changed in a an instance,
 by comparing the value from the instance with its previous value
 
 This went all well, untill I added a too complex variable,
 then the program stopped working, without generating exceptions.
 
 So it seems that comparing a too complex value isn't allowed.

Then you get the wrong impression.

 the variable was something like:
 
   A = [ ndarray, ndarray, ..., [color,color,...], [float, 
 float, ... ] ]
 
 So what I need was something like:
 if  A != A_prev :
 ... do something
 A_prev = A
 
 And this crashes, or at least it doesn't work but also doesn't generate 
 exceptions.
 It does seems to work, if A only contains 1 array.
 
 Why am I not allowed to compare A and A_prev ??

You are allowed and you do in the above code.

 And in general, how complex might a list be to make a valid comparison,
 or what are the rules ?

There are no rules about the complexity.  Lists are compared element wise.
If the lists are of the same length and all elements at the corresponding
indexes compare equal, the lists are considered equal.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fate of itertools.dropwhile() and itertools.takewhile()

2007-12-30 Thread Marc 'BlackJack' Rintsch
On Sat, 29 Dec 2007 15:10:24 -0800, Raymond Hettinger wrote:

 These thoughts reflect my own experience with the itertools module.
 It may be that your experience with them has been different.  Please
 let me know what you think.

I seem to be in a minority here as I use both functions from time to time.
One recipe is extracting blocks from text files that are delimited by a
special start and end line.

def iter_block(lines, start_marker, end_marker):
return takewhile(lambda x: not x.startswith(end_marker),
 dropwhile(lambda x: not x.startswith(start_marker),
   lines))

Maybe these functions usually don't turn up in code that can be called
recipes so often but are useful for themselves.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OOP: How to implement listing al 'Employees'.

2007-12-29 Thread Marc 'BlackJack' Rintsch
On Sat, 29 Dec 2007 01:53:38 -0800, Petar wrote:

 The post of Dennis made me realize of another solution though. To
 create another class called Articles which return multiple articles.
 The only problem I forsee with this that's it's gonna be a very empty
 class.

Then maybe it should not be a class.  Maybe a function returning
`Article`\s would be enough.  This is not Java, not everything has to be
stuffed into classes.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Optional code segment delimiter?

2007-12-29 Thread Marc 'BlackJack' Rintsch
On Sat, 29 Dec 2007 09:20:00 -0800, xkenneth wrote:

 Is it possible to use optional delimiters other than tab and colons?

No.

 And is there an alternate delimiter for statements other than the
 newline?
 
 print this;print that; #for example

Yes.

But both are reasons to yell at you.  ;-)

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Happy Christmas Pythoneers

2007-12-28 Thread Marc 'BlackJack' Rintsch
On Thu, 27 Dec 2007 22:38:44 -0800, Aahz wrote:

 In article [EMAIL PROTECTED],
 Steven D'Aprano  [EMAIL PROTECTED] wrote:
On Wed, 26 Dec 2007 21:32:54 -0800, [EMAIL PROTECTED] wrote:
 
 Hey, my version of the person module doesn't have an is_appropriate_sex
 attribute, but an is_opposite_sex attribute instead. Is this a new
 version?

Generally instances use:

person.is_appropriate_sex = person.is_opposite_sex

but some instances define it as:

person.is_appropriate_sex = not person.is_opposite_sex

It's an implementation detail, you shouldn't worry about it.
 
 Then again, some instances define it as
 
 person.is_appropriate_sex = True

And sometimes it's not that simple but a property and connected with the
caller's history of `champagne.drink()` calls.  The `person.is_pretty`
property is most definitely linked to that call history in many instances.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unicode(s, enc).encode(enc) == s ?

2007-12-28 Thread Marc 'BlackJack' Rintsch
On Fri, 28 Dec 2007 03:00:59 -0800, mario wrote:

 On Dec 27, 7:37 pm, Martin v. Löwis [EMAIL PROTECTED] wrote:
 Certainly. ISO-2022 is famous for having ambiguous encodings. Try
 these:

 unicode(Hallo,iso-2022-jp)
 unicode(\x1b(BHallo,iso-2022-jp)
 unicode(\x1b(JHallo,iso-2022-jp)
 unicode(\x1b(BHal\x1b(Jlo,iso-2022-jp)

 or likewise

 unicode([EMAIL PROTECTED],iso-2022-jp)
 unicode(\x1b$BBB,iso-2022-jp)

 In iso-2022-jp-3, there are even more ways to encode the same string.
 
 Wow, that's not easy to see why would anyone ever want that? Is there
 any logic behind this?
 
 In your samples both of unicode(\x1b(BHallo,iso-2022-jp) and
 unicode(\x1b(JHallo,iso-2022-jp) give uHallo -- does this mean
 that the ignored/lost bytes in the original strings are not illegal
 but *represent nothing* in this encoding?

They are not lost or ignored but escape sequences that tell how the
following bytes should be interpreted '\x1b(B' switches to ASCII and
'\x1b(J' to some roman encoding which is a superset of ASCII, so it
doesn't matter which one you choose unless the following bytes are all
ASCII.  And of course you can use that escape prefix as often as you want
within a string of ASCII byte values.

http://en.wikipedia.org/wiki/ISO-2022-JP#ISO_2022_Character_Sets

 I.e. in practice (in a context limited to the encoding in question)
 should this be considered as a data loss, or should these strings be
 considered equivalent?

Equivalent I would say.  As Unicode they contain the same characters. 
Just differently encoded as bytes.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Strange Behavior: csv module IDLE

2007-12-28 Thread Marc 'BlackJack' Rintsch
On Fri, 28 Dec 2007 18:12:58 -0800, t_rectenwald wrote:

 Within the program, the snippet where I use the csv module is below:
 
 ==
 csvfile = open('foo.csv', 'w')
 writer = csv.writer(csvfile)
 
 for row in rows:
 writer.writerow(row[0:3])
 
 csvfile.close
 ==
 
 The rows object is returned from a database query and is a list of
 tuples.  Now here is the strange thing.  If I run this program
 directly from the command line, i.e.,
 
 D:\test D:\python25\python foo.py
 
 It runs fine, foo.csv is created and all is well.  However, when I run
 it through the IDLE shell as described above, the foo.csv file is
 created but remains empty at 0 bytes.  When I try to delete the file,
 Windows says it is in use.  The only way I can break out of this is by
 restarting the IDLE shell.  In other words, it appears that the shell
 is hanging.
 
 This will run through Task Scheduler, so shouldn't be a problem, but
 I'm worried that I'm coding this wrong for it to be acting this way
 under IDLE.  Any help or explanation would be appreciated.

You are not closing the file so the buffered data is not written to disk. 
To call a function you need the parenthesis, otherwise you are just
referencing it without any effect.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing by reference

2007-12-23 Thread Marc 'BlackJack' Rintsch
On Sun, 23 Dec 2007 03:10:48 -0800, MartinRinehart wrote:

 Bruno, right now I've got this:
 
 def __init__ ( self, t ):
  Constructor, called with array of strings. 
 
 self.text = t
 ...
 
 Some other program will say:
 tok = Toker( text_array )
 tokens = tok.tokenize()
 
 So how does the constructor make the array of strings available to the
 tokenize() method?

Assuming the `__init__()` above belongs to the `Toker` class then the
`tokenize()` method can access it via `self.text` of course.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking for negative values in a list

2007-12-17 Thread Marc 'BlackJack' Rintsch
On Mon, 17 Dec 2007 06:20:23 -0800, vimal wrote:

i have a list of numbers
 
   say a = [1,-1,3,-2,4,-6]
 
   how should i check for negative values in the list

In [6]: a = [1, -1, 3, -2, 4, -6]

In [7]: any(n  0 for n in a)
Out[7]: True

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


<    1   2   3   4   5   6   7   8   9   10   >