Re: OpenOpt install

2007-12-18 Thread Matthieu Brucher
Hi,

My solution was the correct way to go, IIRC, only a few changes were to be
done so that those files were detected correctly (I think there were some
__init__.py files that were not present this may have to do with the fact
that you add a lot of additional paths in sys.path when you load openopt,
but I already told you we should simplify this).

Matthieu

2007/12/18, dmitrey [EMAIL PROTECTED]:

 When earlier OpenOpt versions had been installed there were no
 compiled pyc-files (in destination directory). I called to mailing
 list but no obvious receipt had been achieved. Matthieu had done some
 changes but it yielded other mistakes (no some py-files detected or
 kind of), so I had removed those changes and write my own, for to have
 OO py-files being compiled when installed, because next time when they
 will be run user may not have root permissions, so he will recompile
 source files each time OO starts.

 On Dec 17, 10:27 pm, Robert Kern [EMAIL PROTECTED] wrote:
  dmitrey wrote:
   Use
   python setup.py install
 
  People should be able to run the distutils commands independently.
 
  What are you trying to achieve with this block of code that follows the
 setup()
  call?
 
  new_name = 'tmp55'
  os.rename('scikits', new_name)
  newPath = []
  for directory in sys.path:
  if not 'scikits' in directory: newPath.append(directory)#
 something
  wrong with list.remove()
  sys.path = newPath
  import scikits
  reload(scikits)
  Path = scikits.__path__[0]
  NewPath = os.path.join(Path, 'openopt')
  rmtree(NewPath, True) # True means ignore errors
  copytree(os.path.join(os.path.curdir, new_name, 'openopt'), NewPath)
  NewPath = Path
  compileall.compile_dir(NewPath)
 
  os.rename(new_name, 'scikits')
 
  This just looks like a really bad idea.
 
  --
  Robert Kern
 
  I have come to believe that the whole world is an enigma, a harmless
 enigma
   that is made terrible by our own mad attempt to interpret it as though
 it had
   an underlying truth.
-- Umberto Eco

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




-- 
French PhD student
Website : http://matthieu-brucher.developpez.com/
Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92
LinkedIn : http://www.linkedin.com/in/matthieubrucher
-- 
http://mail.python.org/mailman/listinfo/python-list

Rounding

2007-12-18 Thread katie smith
if i have a number 6.345 and i wanted it to be 6 without subtracting .345 
because it won't always be .345 what do i do?

how do i round to the nearest whole number. Or in this case round down. Is 
there an easy way to round down to the nearest whole number?


  

Never miss a thing.  Make Yahoo your home page. 
http://www.yahoo.com/r/hs

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


Text into a label

2007-12-18 Thread Sam Garson
Hi again.

I am trying to get the text of the selection in a list box and put into a
variable, which is put into a label. i.e., whatever is selected will show in
the label.

However, because at the beginning there is nothing in the listbox (and
therefore no selection), the tuple returned by curselection() is (),
therefore when i try and get() from the linenumber in this tuple, the index
is out of range

here is the section of the program:

box = Listbox(root, bg = '#ebe9ed', relief = 'groove', height = 15)
box.grid(row = 2, columnspan = 2, sticky = W+E, padx = 3)
box.bind(Double-Button-1, DeleteCurrent)

v = StringVar()
number = box.curselection()
v.set = (box.get(int(number[0])))
print number

current = Label(root, textvariable = v)
current.grid(row = 3, columnspan = 2, sticky = W+E, padx = 3)

and here is the error:

Traceback (most recent call last):
  File C:\My Documents\My Python\Notes.py, line 27, in module
v.set = (box.get(int(number[0])))
IndexError: tuple index out of range

How can i get it to only take the variable when i have selected something,
or any other solution!

Thanks,

Sam
-- 
I intend to live forever - so far, so good.

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

Re: strptime() in _strptime.py vs lib-dynload/time.so

2007-12-18 Thread Gabriel Genellina
En Tue, 18 Dec 2007 04:45:25 -0300, [EMAIL PROTECTED] escribió:

 On Dec 17, 8:01 pm, Gabriel Genellina [EMAIL PROTECTED]
 wrote:
 En Mon, 17 Dec 2007 01:53:24 -0300, [EMAIL PROTECTED] escribió:

  actually, the C-version of strptime() is also getting called:
  577650.9600.000   13.9400.000 :0(strptime)

  that's pretty confusing. Does the Python version call the C-version
  (or the other way around)?

 The other way. The strptime function inside the time module  
 (timemodule.c)
 just calls the strptime function written in Python (_strptime.py).
 I have no idea why it's so slow in your case.

 Thanks, that helps. Still I don't understand why the native (C)
 version isn't available.
 Perhaps, it's broken under Windows or something.

 In my test code, strptime() is called approx 60K times (5M times in
 the real code)
 and that takes 6 CPU secs. Thus, we get 100 usecs per call. That's
 much slower
 than running strptime from command line. Perhaps profiling slows
 things down.

 $ python -mtimeit -s 'from time import mktime, strptime'
 'mktime(strptime(070501, %y%m%d))'
 1 loops, best of 3: 40.4 usec per loop

 An easy fix in my case is to avoid strptime() altogether:
  python -mtimeit -s 'from time import mktime; s=070501'
 'mktime((int(s[0:2]), int(s[2:4]), int(s[4:6]),0,0,0,0,0,-1))'
 10 loops, best of 3: 8.6 usec per loop

I think that if your date format is simple enough, parsing it as above may  
be even faster than using the native strptime.

 It would be nice to have access to the native version of strptime()
 for performance reasons.

You can see the story of strptime at http://bugs.python.org/issue474274
Looks like a native strptime may not be always present, or unreliable.  
Perhaps if certain platform has strptime available and it's reliable and  
produces the right results, at configure time it could be detected and  
used instead of the pure Python implementation...

-- 
Gabriel Genellina

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


Re: Rounding

2007-12-18 Thread Vladimir Rusinov
On 12/15/07, katie smith [EMAIL PROTECTED] wrote:

 if i have a number 6.345 and i wanted it to be 6 without subtracting .345
 because it won't always be .345 what do i do?

 how do i round to the nearest whole number. Or in this case round down. Is
 there an easy way to round down to the nearest whole number?


init() ?


-- 
Vladimir Rusinov
GreenMice Solutions: IT-решения на базе Linux
http://greenmice.info/
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: OpenOpt install

2007-12-18 Thread Robert Kern
dmitrey wrote:
 When earlier OpenOpt versions had been installed there were no
 compiled pyc-files (in destination directory). I called to mailing
 list but no obvious receipt had been achieved. Matthieu had done some
 changes but it yielded other mistakes (no some py-files detected or
 kind of), so I had removed those changes and write my own, for to have
 OO py-files being compiled when installed, because next time when they
 will be run user may not have root permissions, so he will recompile
 source files each time OO starts.

Well, the problem there is that you have put code into subdirectories that
aren't packages. Then you manually add the directories to sys.path when you
import scikits.openopt.oo . This is a bad thing to do for several reasons; one
reason is that you don't get the correct .pyc files.

You need to make the directory structure match the package structure. For
example, you currently have the module scikits.openopt.LP in
scikits/openopt/Kernel/LP/LP.py . You have two options:

  * you can make the directory structure match the package structure by moving
the files to the correct location:

$ mv scikits/openopt/Kernel/LP/LP.py scikits/openopt/LP.py

  * you can make the package structure match the directory structure by adding
__init__.py files to the subdirectories and changing the imports to match:

$ touch scikits/openopt/Kernel/__init__.py
$ touch scikits/openopt/Kernel/LP/__init__.py
$ vim scikits/openopt/oo.py
  # 1. Delete the sys.path munging.
  # 2. Change from LP import LP as CLP to from Kernel.LP import LP as 
CLP

-- 
Robert Kern

I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth.
  -- Umberto Eco

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


Re: OpenOpt install

2007-12-18 Thread Matthieu Brucher
OK, in fact distutils can compile every python script without a problem as
long as it is in a package. For instance every solver is in the solvers
folder, but there is no __init__.py file there, so distutils cannot compile
the scripts that are in the subfolders, it is logical.
What you have to do is to modify your oo.py file so that it does not add all
subfolders to the sys.path. Besides, if someone has a subfoler that is named
after one of our folders, the whole scikit can crash : the purpose of
namespaces is to avoid this, so we must use them adequately (that is
scikit.openopt.*), even if it means that the whole scikit architecture must
be rethought.

Matthieu

2007/12/18, Matthieu Brucher [EMAIL PROTECTED]:

 Hi,

 My solution was the correct way to go, IIRC, only a few changes were to be
 done so that those files were detected correctly (I think there were some
 __init__.py files that were not present this may have to do with the fact
 that you add a lot of additional paths in sys.path when you load openopt,
 but I already told you we should simplify this).

 Matthieu

 2007/12/18, dmitrey [EMAIL PROTECTED] :
 
  When earlier OpenOpt versions had been installed there were no
  compiled pyc-files (in destination directory). I called to mailing
  list but no obvious receipt had been achieved. Matthieu had done some
  changes but it yielded other mistakes (no some py-files detected or
  kind of), so I had removed those changes and write my own, for to have
  OO py-files being compiled when installed, because next time when they
  will be run user may not have root permissions, so he will recompile
  source files each time OO starts.
 
  On Dec 17, 10:27 pm, Robert Kern  [EMAIL PROTECTED] wrote:
   dmitrey wrote:
Use
python setup.py install
  
   People should be able to run the distutils commands independently.
  
   What are you trying to achieve with this block of code that follows
  the setup()
   call?
  
   new_name = 'tmp55'
   os.rename('scikits', new_name)
   newPath = []
   for directory in sys.path:
   if not 'scikits' in directory: newPath.append(directory)#
  something
   wrong with list.remove()
   sys.path = newPath
   import scikits
   reload(scikits)
   Path = scikits.__path__[0]
   NewPath = os.path.join(Path, 'openopt')
   rmtree(NewPath, True) # True means ignore errors
   copytree(os.path.join (os.path.curdir, new_name, 'openopt'),
  NewPath)
   NewPath = Path
   compileall.compile_dir(NewPath)
  
   os.rename(new_name, 'scikits')
  
   This just looks like a really bad idea.
  
   --
   Robert Kern
  
   I have come to believe that the whole world is an enigma, a harmless
  enigma
that is made terrible by our own mad attempt to interpret it as
  though it had
an underlying truth.
 -- Umberto Eco
 
  --
  http://mail.python.org/mailman/listinfo/python-list
 



 --
 French PhD student
 Website : http://matthieu-brucher.developpez.com/
 Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92
 LinkedIn : http://www.linkedin.com/in/matthieubrucher




-- 
French PhD student
Website : http://matthieu-brucher.developpez.com/
Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92
LinkedIn : http://www.linkedin.com/in/matthieubrucher
-- 
http://mail.python.org/mailman/listinfo/python-list

Python decompiler

2007-12-18 Thread K.L.
I'm searching a maneuverable python bytecode decompiler. There is one
named 'decompyle', but it doesn't support Python2.5 and too hard to
use. And the 'depython'(http://www.depython.net/) is good enough
except it cannot process file more than 5kb.

Is there some else available? I'm novice at python. Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


No tab completion if sys.stdout is redirected

2007-12-18 Thread Dirk Loss
Hi,

I want to have tab completion in my program for interactive input.
Using readline and rlcompleter this works nicely. But I also have to
catch and modify all print output, so I redirect sys.stdout
to a custom file-like object. The problem is: After the redirection,
readline support seems suddenly disabled. Why?

Here's an example:

- cut 
import sys
import rlcompleter
import readline

class DottedWriter(object):
 Just a simple example for a sys.stdout wrapper
 def __init__(self, orig_stdout):
 self.orig_stdout = orig_stdout

 def write(self, text):
 self.orig_stdout.write(. + text)

readline.parse_and_bind(tab: complete)
mywriter = DottedWriter(sys.stdout)

raw_input(Press TAB to see that completion works. Then press ENTER:)
print Replacing sys.stdout with a custom file-like object...
sys.stdout = mywriter
raw_input(Now tab completion doesn't work anymore. Please try:)
- cut 

In the first raw_input() call, tab completion works, in the second it
doesn't. Am I doing something wrong here or is it a bug?

Reproduced on Windows (with pyreadline 1.5) and Linux (standard readline
module), both using Python 2.5.1.

Things I have tried without success:
- Simulate all other methods of sys.stdout with __getattr__
   def __getattr__(self, name): return getattr(self.orig_stdout, name)
- Use other forms of interactive input
   * import code; code.interact()
   * input()

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


Re: Rounding

2007-12-18 Thread Lars Johansen
that does not round up.. int(round(6.345)) maybe
tir, 18.12.2007 kl. 11.53 +0300, skrev Vladimir Rusinov:
 
 
 On 12/15/07, katie smith [EMAIL PROTECTED] wrote:
 if i have a number 6.345 and i wanted it to be 6 without
 subtracting .345 because it won't always be .345 what do i do?
 
 how do i round to the nearest whole number. Or in this case
 round down. Is there an easy way to round down to the nearest
 whole number?
 
 init() ? 
 
 
 
 
 -- 
 Vladimir Rusinov
 GreenMice Solutions: IT-решения на базе Linux
 http://greenmice.info/ 
 -- 
 http://mail.python.org/mailman/listinfo/python-list

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

Re: Rounding

2007-12-18 Thread John Machin
On Dec 18, 7:53 pm, Vladimir Rusinov [EMAIL PROTECTED]
wrote:
 On 12/15/07, katie smith [EMAIL PROTECTED] wrote:



  if i have a number 6.345 and i wanted it to be 6 without subtracting .345
  because it won't always be .345 what do i do?

  how do i round to the nearest whole number. Or in this case round down. Is
  there an easy way to round down to the nearest whole number?

 init() ?

Perhaps you mean int. The OP may also be interested in another built-
in function, just in case a float result or more versatility is
needed; it's called round.



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


Re: Rounding

2007-12-18 Thread Chris
On Dec 18, 10:53 am, Vladimir Rusinov [EMAIL PROTECTED]
wrote:
 On 12/15/07, katie smith [EMAIL PROTECTED] wrote:



  if i have a number 6.345 and i wanted it to be 6 without subtracting .345
  because it won't always be .345 what do i do?

  how do i round to the nearest whole number. Or in this case round down. Is
  there an easy way to round down to the nearest whole number?

 init() ?

 --
 Vladimir Rusinov
 GreenMice Solutions: IT-решения на базе Linuxhttp://greenmice.info/

You can either do:

input_number = 6.345
from math import floor
floor( input_number )
 6.0
This will return a float rounded down.

   or alternatively
int( input_number )
 6
Which will return an integer data-type.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Rounding

2007-12-18 Thread Vladimir Rusinov
On 12/18/07, Lars Johansen [EMAIL PROTECTED] wrote:

 that does not round up..


Yep, this is truncation. I'd read the question better.

-- 
Vladimir Rusinov
GreenMice Solutions: IT-решения на базе Linux
http://greenmice.info/
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: New to Python Would like debug advice

2007-12-18 Thread Bruno Desthuilliers
Ramsey Nasser a écrit :
 On Dec 17, 2007 9:17 PM, PatrickMinnesota [EMAIL PROTECTED] wrote:
 Yep, I'm new to the language, it's been a couple of months.

 I opted for gvim and console window for developing on a Windows XP
 box.  I'm not a huge fan of IDEs except for when I need some
 debugging.  I've done my googling and see a bunch of options out there
 for a debugging solution for Python on Windows.

 I've used Eclipse for a few years for Java development and I
 understand there is a Python module for it that might make sense.

 What I'm looking for is advice on what to use to debug general Python
 programs at the source level, some will be graphical.  If the eclipse
 route is the way to go, that's fine, but I'm wondering what other
 options people have good luck with.  Keep in mind I will probably
 continue to use Vi/Emacs and a console window for my main development.

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

 
 Debugging Python in eclipse is great.

Specially thru ssh on an overloaded web server...

 It's the same as debugging in
 Java, so you don't have to learn any new interface or concepts to get
 started.

There's some differences here. I don't even dream of trying to write any 
non-trivial Java progarm without a debugger. OTHO, I already wrote a few 
non-trivial Python programs (and some others that would have been 
non-trivial in Java) without having to use pdb - a couple trace and the 
interactive shell where quite enough. So perhaps there's at least one 
new concept to learn here : you don't need a mammoth IDE to be 
productive with an agile language.

My 2 cents.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to read a binary file into a mysql table

2007-12-18 Thread Hans Müller
Sorry, I found the mistake:

There is more than one blob type, blob as a default stores only 64k of data.
LONGBLOB has a 4G limit which is Ok for my purposes.

Happy Christmas to all,

Hans


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


Re: More than one interpreter per process?

2007-12-18 Thread Roger Binns
sturlamolden wrote:
 If one can have more than one interpreter in a single process, 

You can.  Have a look at mod_python and mod_wsgi which does exactly
this.  But extension modules that use the simplified GIL api don't work
with them (well, if at all).

 Most of the conversion of the current Python C API could be automated.

The biggest stumbling block is what to do when the external environment
makes a new thread and then eventually calls back into Python.  It is
hard to know which interpretter that callback should go to.

You are also asking for every extension module to have to be changed.
The vast majority are not part of the Python source tree and would also
have to support the versions before a change like this.

You would have more luck getting this sort of change into Python 3 since
that requires most extension modules to be modified a bit (eg to deal
with string and unicode issues).

But before doing that, why not show how much better your scheme would
make things.  The costs of doing it are understood, but what are the
benefits in terms of cpu consumption, memory consumption, OS
responsiveness, cache utilisation, multi-core utilisation etc.  If the
answer is 1% then that is noise.

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


Re: How to read a binary file into a mysql table

2007-12-18 Thread Hans Müller
Hello,

thanks a lot for the Binary(). This does the trick, now I can import all my 
binary data.
But now I found the next problem:
The Blob is now limited to 65535 Bytes. I love all these stone age (16bit) 
limits on my 64bit machines...
All bigger files a truncated.

Has someone an idea how to solve this ?


Greetings

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


Re: Best way to protect my new commercial software.

2007-12-18 Thread Jan Claeys
Op Fri, 14 Dec 2007 16:54:35 +, schreef Grant Edwards:

 Uh what?  I don't know what country you're in, but in the US, it doesn't
 take any time at all to copyright something.  The mere act of writing
 something copyrights it.  I thought it was the same in Europe as well.

No, it's only copyrighted when you _publish_ it.


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


operator module isSequenceType with builtin set produces False

2007-12-18 Thread English, Mark
X-Replace-Address:
[EMAIL PROTECTED]
receding_xxxs_.com

This wasn't what I was expecting, so I thought I'd ask those more
knowledgeable, which is pretty much everybody.
Same result on Python 2.3.5 and Python 2.5.1 installed from python.org
binaries on Windows XP.

 try: set
 except NameError: from sets import Set as set
 class myset_fails(set): pass
 class myset_works(set):
 def __getitem__(self): pass
 s = set()
 fails = myset_fails()
 works = myset_works()
 import operator
 operator.isSequenceType(s) #Not what I expected
False
 operator.isSequenceType(fails) #Not what I expected either
False
 operator.isSequenceType(works) #A hint at what isSequenceType does ?
True

Are sets not sequences ? I didn't think the isSequenceDisclaimer gave
false negatives.
See Raymond Hettinger's post here too:
http://groups.google.co.uk/group/comp.lang.python/tree/browse_frm/thread
/bd04db20cc1f23bb/36f1f48bb7be1e4b?hl=enrnum=1q=set+isSequenceType_do
ne=%2Fgroup%2Fcomp.lang.python%2Fbrowse_frm%2Fthread%2Fbd04db20cc1f23bb%
2F0454f5debc01c20d%3Fhl%3Den%26lnk%3Dgst%26q%3Dset%2BisSequenceType%26#d
oc_0454f5debc01c20d

Although there are suggestions that it means simply that you're headed
in the wrong direction design wise:
http://www.mail-archive.com/[EMAIL PROTECTED]/msg11576.html

but then why have isSequenceType at all ?


Not particularly vital. Just implementing __str__ on some class and if
one of the members was a sequence
I was going to format that bit of data in brackets.

Thanks,
Mark

__

This email is intended only for the use of the individual(s) to whom it is 
addressed and may be privileged and confidential.
Unauthorised use or disclosure is prohibited.If you receive This e-mail in 
error, please advise immediately and delete the original message.
This message may have been altered without your or our knowledge and the sender 
does not accept any liability for any errors or omissions in the message.
-- 
http://mail.python.org/mailman/listinfo/python-list

checking a string against multiple patterns

2007-12-18 Thread tomasz
Hi,

here is a piece of pseudo-code (taken from Ruby) that illustrates the
problem I'd like to solve in Python:

str = 'abc'
if str =~ /(b)/ # Check if str matches a pattern
  str = $` + $1# Perform some action
elsif str =~ /(a)/ # Check another pattern
  str = $1 + $'# Perform some other action
elsif str =~ /(c)/
  str = $1
end

The task is to check a string against a number of different patterns
(containing groupings).
For each pattern, different actions need to be taken.

In Python, a single match of this kind can be done as follows:

str = 'abc'
match = re.search( '(b)' , str )
if match: str = str[0:m.start()] + m.group(1)# I'm not sure if
this way of accessing 'pre-match'
   # is
optimal, but let's ignore it now

The problem is that you you can't  extend this example to multiple
matches with 'elif'
because the match must be performed separately from the conditional.

This obviously won't work in Python:

if match=re.search( pattern1 , str ):
  ...
elif match=re.search( pattern2 , str ):
  ...

So the only way seems to  be:

match = re.search( pattern1 , str ):
if match:
   
else:
   match = re.search( pattern2 , str ):
   if match:
  
   else:
   match = re.search( pattern3 , str ):
   if match:
   

and we end up having a very nasty, multiply-nested code.

Is there an alternative to it? Am I missing something? Python doesn't
have special variables $1, $2 (right?) so you must assign the result
of a match to a variable, to be able to access the groups.

I'd appreciate any hints.

Tomasz







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


Re: python-xlib question

2007-12-18 Thread giovanni . iovino
Solved,

I solved using Xtest fake_input, hoping helping other people i post
the code:

#!/usr/bin/env python
import Xlib.display
import Xlib.X
import Xlib.XK
import Xlib.error
import Xlib.ext.xtest

display = Xlib.display.Display()
def mouse_click(button):   #button= 1 left, 2 middle, 3 right
Xlib.ext.xtest.fake_input(display,Xlib.X.ButtonPress, button)
display.sync()
Xlib.ext.xtest.fake_input(display,Xlib.X.ButtonRelease,
button)
display.sync()

bye,
Giovanni
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking a string against multiple patterns

2007-12-18 Thread kib
tomasz a écrit :

 Is there an alternative to it? Am I missing something? Python doesn't
 have special variables $1, $2 (right?) so you must assign the result
 of a match to a variable, to be able to access the groups.
 
Hi Thomasz,

See ie :

http://www.regular-expressions.info/python.html [Search and Replace section]

And you'll see that Python supports numbered groups and even named 
groups in regular expressions.

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


Re: checking a string against multiple patterns

2007-12-18 Thread Gabriel Genellina
On 18 dic, 09:41, tomasz [EMAIL PROTECTED] wrote:

 Hi,

 here is a piece of pseudo-code (taken from Ruby) that illustrates the
 problem I'd like to solve in Python:

 str = 'abc'
 if str =~ /(b)/ # Check if str matches a pattern
   str = $` + $1# Perform some action
 elsif str =~ /(a)/ # Check another pattern
   str = $1 + $'# Perform some other action
 elsif str =~ /(c)/
   str = $1
 end

 The task is to check a string against a number of different patterns
 (containing groupings).
 For each pattern, different actions need to be taken.

 In Python, a single match of this kind can be done as follows:

 str = 'abc'
 match = re.search( '(b)' , str )
 if match: str = str[0:m.start()] + m.group(1)# I'm not sure if
 this way of accessing 'pre-match'
# is
 optimal, but let's ignore it now

 The problem is that you you can't  extend this example to multiple
 matches with 'elif'
 because the match must be performed separately from the conditional.

 This obviously won't work in Python:

 if match=re.search( pattern1 , str ):
   ...
 elif match=re.search( pattern2 , str ):
   ...

 So the only way seems to  be:

 match = re.search( pattern1 , str ):
 if match:

 else:
match = re.search( pattern2 , str ):
if match:
   
else:
match = re.search( pattern3 , str ):
if match:


 and we end up having a very nasty, multiply-nested code.

Define a small function with each test+action, and iterate over them
until a match is found:

def check1(input):
  match = re.search(pattern1, input)
  if match:
return input[:match.end(1)]

def check2(input):
  match = re.search(pattern2, input)
  if match:
return ...

def check3(input):
  match = ...
  if match:
return ...

for check in check1, check2, check3:
  result = check(input)
  if result is not None:
break
else:
  # no match found

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


Re: checking a string against multiple patterns

2007-12-18 Thread grflanagan
On Dec 18, 1:41 pm, tomasz [EMAIL PROTECTED] wrote:
 Hi,

 here is a piece of pseudo-code (taken from Ruby) that illustrates the
 problem I'd like to solve in Python:

 str = 'abc'
 if str =~ /(b)/ # Check if str matches a pattern
   str = $` + $1# Perform some action
 elsif str =~ /(a)/ # Check another pattern
   str = $1 + $'# Perform some other action
 elsif str =~ /(c)/
   str = $1
 end

 The task is to check a string against a number of different patterns
 (containing groupings).
 For each pattern, different actions need to be taken.


In the `re.sub` function (and `sub` method of regex object), the
`repl` parameter can be a callback function as well as a string:

http://docs.python.org/lib/node46.html

Does that help?

Eg.

def multireplace(text, mapping):
rx = re.compile('|'.join(re.escape(key) for key in mapping))
def callback(match):
key = match.group(0)
repl = mapping[key]
log.info(Replacing '%s' with '%s', key, repl)
return repl
return rx.subn(callback, text)

(I'm not sure, but I think I adapted this from: 
http://effbot.org/zone/python-replace.htm)

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


Re: checking a string against multiple patterns

2007-12-18 Thread Tim Chase
 Define a small function with each test+action, and iterate over them
 until a match is found:
 
 def check1(input):
   match = re.search(pattern1, input)
   if match:
 return input[:match.end(1)]
 
 def check2(input):
   match = re.search(pattern2, input)
   if match:
 return ...
 
 for check in check1, check2, check3:
   result = check(input)
   if result is not None:
 break
 else:
   # no match found

Or, one could even create a mapping of regexps-functions:

 def function1(match):
   do_something_with(match)

 def function2(match):
   do_something_with(match)

 def default_function(input):
   do_something_with(input)

 function_mapping = (
   (re.compile(pattern1), function1),
   (re.compile(pattern2), function2),
   (re.compile(pattern3), function1),
   )

 def match_and_do(input, mapping):
   for regex, func in mapping:
 m = regex.match(input)
 if m: return func(m)
   return default_function(input)

 result = match_and_do(Hello world, function_mapping)

In addition to having a clean separation between patterns and
functions, and the mapping between them, this also allows wiring
multiple patterns to the same function (e.g. pattern3-function1)
and also allows specification of the mapping evaluation order.

-tkc



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


.NET and Python Integration Problem and PDF Library (Need Help and Suggestions)

2007-12-18 Thread Ravi Kumar
Hi.
First I am explaining the Problem so it would not get messed up. :)

== PROBLEM 
I have to integrate a small part in .NET Projects. .NET project is
actually all Web-based application, user interface is Web-page for
multiple actions.
But a backend component of project needs PDF File manipulation.
Manipuation is limited to splitting pages, removing certain pages,
joining pages, finding certain text information (Title/Author/No. of
Pages/Orientation of each page etc), and page orientation maipulation
(rotating pages clockwise and anticlockwise, on degree parameter,
left/right/flip etc).
.NET guys are failing here, so I proposed to do that component in Python.
But problem is, how to integrate Python in .NET Web Application. I am
looking on IRONPYTHON, and thats the only point seemed to me. Also, as
I am not an expert in Python, I have transition from Perl and PHP to
python. So right now, my applciation architecture would little bit be
inexperienced and not enterprise ready. But every component in project
is being worked on Enterprise grade.
Now,
I want to integrate Python implementation for PDF works, and that
would be called from .NET (C#) processes supplying required
parameters. Since the whole application would be implemented on MS
Windows Server, so I am bit lacking the freedom of library usage as in
Linux.

Also looking for best PDF library which doesn't have any or many
dependencies and that dependencies can be successfully installed. I
will also need an XML Library to write down the logs and
instructions+information for next component which handles Printing.

=

Therefore, I am seeking all the precious (even small or one-liner)
advices from you. Please suggest me every possible things that come in
your mind. Things on high priorities right now are:



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


Re: Best way to protect my new commercial software.

2007-12-18 Thread Piet van Oostrum
 Jan Claeys [EMAIL PROTECTED] (JC) wrote:

JC Op Fri, 14 Dec 2007 16:54:35 +, schreef Grant Edwards:
 Uh what?  I don't know what country you're in, but in the US, it doesn't
 take any time at all to copyright something.  The mere act of writing
 something copyrights it.  I thought it was the same in Europe as well.

JC No, it's only copyrighted when you _publish_ it.

Not here in the Netherlands. It is `the exclusive right of the maker of a
work to publish or copy the work' (loose translation of the introduction of
the law). Otherwise someone else could publish it if he got hold of it in
some legitimate way.
-- 
Piet van Oostrum [EMAIL PROTECTED]
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
Private email: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: .NET and Python Integration Problem and PDF Library (Need Help and Suggestions)

2007-12-18 Thread Ravi Kumar
In continuation of last mail [since pressing tab+space sent the mail :( ]
Things on high priorities right now are:
- How to integrate Python calling from .NET
- Any suggestions for optimizations that would prevent overburden to
application due to IronPython interpretation calling, if any, or does
such things happen.
- Pointers to good resources
- Any step in such kind of situation, so to make it Enterprise Grade
application components
- your opinion with available PDF Libraries, that are best among. Also
which library to use for Windows server platform (there is limitation
on installing long chain libraries that include other deep
dependencies too). A pure python PDF library would be good, but which
one.
-Which XML Library is pure python based.


More questions will follow up :)
And I hope, people will reply me.


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


Does fileinput.input() read STDIN all at once?

2007-12-18 Thread Adam Funk
I'm using this sort of standard thing:

   for line in fileinput.input():
  do_stuff(line)

and wondering whether it reads until it hits an EOF and then passes
lines (one at a time) into the variable line.  This appears to be the
behaviour when it's reading STDIN interactively (i.e. from the
keyboard).

As a test, I tried this:

   for line in fileinput.input():
  print '**', line

and found that it would print nothing until I hit Ctl-D, then print
all the lines, then wait for another Ctl-D, and so on (until I pressed
Ctl-D twice in succession to end the loop).

Is it possible to configure this to pass each line of input into line
as it comes?

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


Re: Another newbie design question

2007-12-18 Thread MartinRinehart
Fortran (1957) had line comments. C (1972) replaced these with non-
nested block comments. C++ (1983) added here-to-EOL comments. Python
(1991) keeps here-to-EOL comments but replaces block comments with
multi-line quotes. Block comments and multi-line quotes both serve the
same purpose as doc comments. Block comments, especially if they nest,
are helpful for commenting out code. Multi-line quotes serve to add
text.

Is Python, in this particular, an advance over C++?

I wrote a lot of Java (here-to-EOL and block comments) without ever
feeling the need for multi-line quotes. I've written a little Perl and
found multi-line quotes useful for responding to -help switches. On
the other hand -help switches are very old-fashioned, a direction I'll
not be pointing my tiny beginner's language.

(A brief article on programming language geneology is at
http://www.MartinRinehart.com/articles/history-programming-languages.html
.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: No tab completion if sys.stdout is redirected

2007-12-18 Thread Bjoern Schliessmann
Dirk Loss wrote:
 I want to have tab completion in my program for interactive input.
 Using readline and rlcompleter this works nicely. But I also have
 to catch and modify all print output, so I redirect sys.stdout
 to a custom file-like object. The problem is: After the
 redirection, readline support seems suddenly disabled. Why?

readline module applies its autocompletion functions to (and only
to) sys.stdout.

Regards,


Björn

-- 
BOFH excuse #350:

paradigm shift...without a clutch

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


Re: More than one interpreter per process?

2007-12-18 Thread sturlamolden
On 18 Des, 05:46, Michael L Torrie [EMAIL PROTECTED] wrote:

 How would this handle python resources that a programmer would want to
 share among the threads?  What facilities for IPC between the
 interpreters would be used?

There would be no IPC as they would live in the same process. A thread-
safe queue would suffice. Python objects would have to be serialized
before placed in the queue. One could also allow NumPy-like arrays in
two separate interpreters to share the same memory buffer.

With an emulated fork() the whole interpreter would be cloned,
possibly deferred in a 'copy on write' scheme.

Multiple processes and IPC is what we have today with e.g. mpi4py.






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


Re: Another newbie design question

2007-12-18 Thread Sion Arrowsmith
 [EMAIL PROTECTED] wrote:
I've designed a language, Decaf, for beginners. I've got block
comments but not multi-line strings.

If you can only have one or the other, which is more helpful?

Given a one-or-the-other choice, any editor worth using can do
comment/uncomment region, and if only to-EOL comments are
available, it will do that for you instead of using block
comments. So block comments are not really a useful language
feature. Unless you're expecting your beginners to grind out
their code in Notepad.

On the other hand, they are completely orthogonal features.
Multi-line strings in Python are not comments, and treating
them as such is as misguided as using raw strings for Windows
filenames. What would you have to say about a language which
had no specialised comment syntax whatsoever, and expected
you to use semantically irrelevent string literals?

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
   Frankly I have no feelings towards penguins one way or the other
-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: More than one interpreter per process?

2007-12-18 Thread sturlamolden
On 18 Des, 10:24, Roger Binns [EMAIL PROTECTED] wrote:

 The biggest stumbling block is what to do when the external environment
 makes a new thread and then eventually calls back into Python.  It is
 hard to know which interpretter that callback should go to.

Not if you explicitely hav to pass a pointer to the interpreter in
every API call, which is what I suggested.


 You are also asking for every extension module to have to be changed.
 The vast majority are not part of the Python source tree and would also
 have to support the versions before a change like this.

It would break a lot of stuff.

But porting could be automated by a simple Python script. It just
involves changing PySomething(...) to PySomething(env, ...), with env
being a pointer to the interpreter. Since an extension only needs to
know about a single interpreter, it could possibly be done by
preprocessor macros:

#define PySomething(var) PySomething(env, var)

 You would have more luck getting this sort of change into Python 3 since
 that requires most extension modules to be modified a bit (eg to deal
 with string and unicode issues).

PEPs are closed for Python 3.

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


New+old-style multiple inheritance

2007-12-18 Thread [EMAIL PROTECTED]
We are trying to monkey-patch a third-party library that mixes new and
old-style classes with multiple inheritance.  In so doing we have
uncovered some unexpected behaviour:

quote
class Foo:
pass

class Bar(object):
pass

class Baz(Foo,Bar):
pass

# Monkey-patch Foo to add a special method
def my_nonzero(self):
print my_nonzero called
return False
Foo.__nonzero__ = my_nonzero

b = Baz()

print doing the test on Baz(Foo,Bar).  Should return false
if b:
print true
else:
print false
/quote

Produces this output:

  doing the test on Baz(Foo,Bar).  Should return false
  true

With some experimentation it is clear that this behaviour only occurs
when you combine new+old-style multiple inheritance, monkey-patching
and special methods.  If Foo and Bar are either old or new-style it
works.  calling b.__nonzero__() directly works.  Defining __nonzero__
within Foo works.

I know this level of messing with python internals is a bit risky but
I'm wondering why the above code doesn't work.

Any ideas?

Cheers,
Stephen.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: More than one interpreter per process?

2007-12-18 Thread sturlamolden
On 18 Des, 10:24, Roger Binns [EMAIL PROTECTED] wrote:

 You can.  Have a look at mod_python and mod_wsgi which does exactly
 this.  But extension modules that use the simplified GIL api don't work
 with them (well, if at all).

mod_python implements use Py_NewInterpreter() to create sub-
interpreters. They all share the same GIL. The GIL is declared static
in ceval.c, and shared for the whole process. But ok, if
PyEval_AquireLock() would take a pointer to a 'sub-GIL', sub-
interpreters could run concurrent on SMPs. But it would require a
separate thread scheduler in each subprocess.











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


Re: Best way to protect my new commercial software.

2007-12-18 Thread Preston Landers
Jan Claeys([EMAIL PROTECTED])@2007.12.18 12:06:08 +:
 Op Fri, 14 Dec 2007 16:54:35 +, schreef Grant Edwards:
 
  Uh what?  I don't know what country you're in, but in the US, it doesn't
  take any time at all to copyright something.  The mere act of writing
  something copyrights it.  I thought it was the same in Europe as well.
 
 No, it's only copyrighted when you _publish_ it.


If we're still talking about US law here you are incorrect.

http://www.copyright.gov/help/faq/faq-general.html#mywork

Quoting:

* When is my work protected?

Your work is under copyright protection the moment it is created and
fixed in a tangible form that it is perceptible either directly or
with the aid of a machine or device.

* Do I have to register with your office to be protected?

No. In general, registration is voluntary. Copyright exists from the
moment the work is created. You will have to register, however, if you
wish to bring a lawsuit for infringement of a U.S. work. See Circular
1, Copyright Basics, section 'Copyright Registration.'

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


Re: Python on Leopard issues

2007-12-18 Thread arthurwoll
Hi Folks: I am new to python, and, (thanks to on-site help) just
installed ipython, matplotlib, numpy and scipy on my PPC running
Leopard (10.5.1). Since scipy.org's install page is out-dated -- it
recommends beginning by re-installing python (http://www.scipy.org/
Installing_SciPy/Mac_OS_X) -- I thought I would document my steps:

1. My experience is that the python that ships with 10.5.1 (developer
tools / xcode) is both up to date (version 2.5.1) and works FINE.
(e.g. without doing anything, you can start up python from a command
line, and even arrow up to previous commands).

2. ipython: Installing ipython (ipython-0.8.2.tar.gz) went just as
advertised here: http://ipython.scipy.org/moin/Download.

3. fortran: Installed gfortran (gfortran-4.2.1.dmg) from (http://
r.research.att.com/tools/) -- no trouble.

4. FFTW: Installed the fftw libraries (3.1.2) as described on
scipy.org -- no trouble.

5. Numpy: built, installed numpy as described on scipy.org. No trouble
(to test, use import numpy followed by, e.g. numpy.test(1,10) from
within python

6. Scipy: Trouble. The necessary steps are documented but not so easy
to find.   There are two issues.

6.a: Although my new version of numpy is installed, python gives
(mistaken) precedence to a built in version.  To fix this, I placed
the line:
export PYTHONPATH=/Library/Python/2.5/site-packages
in my shell configuration file: ~/.profile

6.b: Although I just installed gfortran, the python build step doesn't
know to use it. Instead of python setup.py build you need to use
python setup.py config_fc --fcompiler=gfortran build

6.c: The installation step sudo python setup.py install worked, as
does import scipy.  scipy.test(1,10) gives two failures, but 1714
successes, which is an A+ on any test.  For the record the failures
are

==
FAIL: check loadmat case sparse
--
Traceback (most recent call last):
  File /Library/Python/2.5/site-packages/scipy/io/tests/test_mio.py,
line 85, in cc
self._check_case(name, files, expected)
  File /Library/Python/2.5/site-packages/scipy/io/tests/test_mio.py,
line 80, in _check_case
self._check_level(k_label, expected, matdict[k])
  File /Library/Python/2.5/site-packages/scipy/io/tests/test_mio.py,
line 63, in _check_level
decimal = 5)
  File /Library/Python/2.5/site-packages/numpy/testing/utils.py,
line 232, in assert_array_almost_equal
header='Arrays are not almost equal')
  File /Library/Python/2.5/site-packages/numpy/testing/utils.py,
line 217, in assert_array_compare
assert cond, msg
AssertionError:
Arrays are not almost equal
test sparse; file /Library/Python/2.5/site-packages/scipy/io/tests/./
data/testsparse_6.5.1_GLNX86.mat, variable testsparse
(mismatch 46.67%)
 x: array([[  3.03865194e-319,   3.16202013e-322,   1.04346664e-320,
  2.05531309e-320,   2.56123631e-320],
   [  3.16202013e-322,   0.e+000,   0.e+000,...
 y: array([[ 1.,  2.,  3.,  4.,  5.],
   [ 2.,  0.,  0.,  0.,  0.],
   [ 3.,  0.,  0.,  0.,  0.]])

==
FAIL: check_dot (scipy.lib.tests.test_blas.test_fblas1_simple)
--
Traceback (most recent call last):
  File /Library/Python/2.5/site-packages/scipy/lib/blas/tests/
test_blas.py, line 76, in check_dot
assert_almost_equal(f([3j,-4,3-4j],[2,3,1]),-9+2j)
  File /Library/Python/2.5/site-packages/numpy/testing/utils.py,
line 158, in assert_almost_equal
assert round(abs(desired - actual),decimal) == 0, msg
AssertionError:
Items are not equal:
 ACTUAL: (-1.998528003692627+1.0484833485089376e-37j)
 DESIRED: (-9+2j)

--

7. Matplotlib: Retrieved here: (http://sourceforge.net/projects/
matplotlib) and installed following the normal steps: (python
setup.py build,  sudo python setup.py install). To test this one,
run python as:
ipython -pylab
Typing, e.g. plot([1,2,3]) makes a nice plot window...

NOTE:  matplotlib requires libraries (freetype, libpng, zlib) that
were installed (and presumably found by matplotlib) during my
macports (http://www.macports.org/index.php) installation
ImageMagick.


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


Re: Debugging pipe IPC

2007-12-18 Thread Ian Clark
Jim B. Wilson wrote:
 Ian Clark wrote:
 Jim B. Wilson wrote:
 ...
 The child/client sends requests on its stdout and receives responses 
 on stdin.
 So, why can't you just run this client on the command line and let the 
 shell handle stdin/stdout for you?
 
 I'm not sure I understand the topology of your proposal?  And, it's 
 certainly possible the shell has mystical powers of which I am unaware.
 
 Are you suggesting a run client that spews the mother's messages to the 
 terminal, and I somehow cut/paste them into the client, running with 
 stdin/stdout unconnected to anything but me?  Or is there some 
 combination of tee, etal.,  I can lash together so that my commands (to 
 the client) don't get mixed up with mother's messages?
 
 Some such arrangement would surely help.  I often forget the stderr, 
 on my scratch-head debugging prints, and mother gets quite upset when 
 the incoming message doesn't fit the mold :)
 
 Jim

What I'm suggesting is to run the following from the shell: python 
internal_python_program.py. Then you type into the terminal whatever 
'mother' was sending it (Clean your room! most like) and see what it 
spits back. If the script is simply reading from stdin and writing to 
stdout there shouldn't be much of a problem. The hardest part might be 
figuring out what 'mother' actually sends it.

If it's very verbose you can type it out once to a file and redirect 
that file to the python process: python internal_python_program.py  
file_with_mother_commands.txt.

Another idea is to open a file somewhere and write your debug output to 
that. I would also suggest the logging[1] module as well. It's very 
handy for his sort of thing.

Ian

[1] http://docs.python.org/lib/module-logging.html

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


Re: embedding filedialog in a frame in tkinter

2007-12-18 Thread [EMAIL PROTECTED]

 Try using Tix, a Tkinter extension included in the Python library. It
 provides a DirList widget:



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


Re: checking a string against multiple patterns

2007-12-18 Thread Hrvoje Niksic
tomasz [EMAIL PROTECTED] writes:

 here is a piece of pseudo-code (taken from Ruby) that illustrates the
 problem I'd like to solve in Python:
[...]

I asked the very same question in
http://groups.google.com/group/comp.lang.python/browse_frm/thread/3e8da954ff2265e/4deb5631ade8b393
It seems that people either write more elaborate constructs or learn
to tolerate the nesting.

 Is there an alternative to it?

A simple workaround is to write a trivial function that returns a
boolean, and also stores the match object in either a global storage
or an object.  It's not really elegant, especially in smaller scripts,
but it works:

def search(pattern, s, store):
match = re.search(pattern, s)
store.match = match
return match is not None

class MatchStore(object):
pass   # irrelevant, any object with a 'match' attr would do

where = MatchStore()
if search(pattern1, s, where):
pattern1 matched, matchobj in where.match
elif search(pattern2, s, where):
pattern2 matched, matchobj in where.match
...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to protect my new commercial software.

2007-12-18 Thread Grant Edwards
On 2007-12-18, Jan Claeys [EMAIL PROTECTED] wrote:
 Op Fri, 14 Dec 2007 16:54:35 +, schreef Grant Edwards:

 Uh what?  I don't know what country you're in, but in the US, it doesn't
 take any time at all to copyright something.  The mere act of writing
 something copyrights it.  I thought it was the same in Europe as well.

 No, it's only copyrighted when you _publish_ it.

Interesting.  So, in Europe, if somebody steals something you
wrote before you get it published, they're free to do with it
as they please?

I'm glad it doesn't work that way here in the US.  Over here,
something is copyrighted as soon as it's written (actually I
think the phrase is fixed in a medium or something like
that).

-- 
Grant Edwards   grante Yow! I have accepted
  at   Provolone into my life!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


clearing text on canvas

2007-12-18 Thread [EMAIL PROTECTED]
hi
i am new to  tkinter and would like some help with canvas

i am doing  validation of contents of a folder  and need to show the
ok/error messages on a canvas

resultdisplay =Canvas(...)
errmessage=error!
okmessage=dir validation ok!

if dirvalidate is False:
resultdisplay.create_text(1,50,anchor=W,text=errmessage,width=175)

else:
self.resultdisplay.create_text(1,50,anchor=W,text=okmessage,width=175)


my problem is that if validation succeeds or fails the text created on
canvas is displayed over the previous created text
I need to clear the previous text from the canvas before creating new
text
can someone help?
dn

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


Re: More than one interpreter per process?

2007-12-18 Thread Aahz
In article [EMAIL PROTECTED],
sturlamolden  [EMAIL PROTECTED] wrote:
On 18 Des, 10:24, Roger Binns [EMAIL PROTECTED] wrote:
 
 You would have more luck getting this sort of change into Python 3 since
 that requires most extension modules to be modified a bit (eg to deal
 with string and unicode issues).

PEPs are closed for Python 3.

That's true for core interpreter changes and only applies to Python 3.0.
Overall, what Roger said is true: if there is any hope for your proposal,
you must ensure that you can make it happen in Python 3.
-- 
Aahz ([EMAIL PROTECTED])   * http://www.pythoncraft.com/

Typing is cheap.  Thinking is expensive.  --Roy Smith
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another newbie design question

2007-12-18 Thread MartinRinehart
Sion Arrowsmith wrote:
 Given a one-or-the-other choice, any editor worth using can do
 comment/uncomment region, and if only to-EOL comments are
 available, it will do that for you instead of using block
 comments. So block comments are not really a useful language
 feature.

I'd expect the complete beginner to start in Notepad, and stay there
for just long enough to realize that something better is needed.
region commenting might be the perfect reason for upgrading.

On the other hand, block comments are very useful for documentation.

On the other, other hand, commenting out a region as the editors do
makes it very obvious that the code is dormant.

On yet another hand, editors also colorize, so the commented-out
nature of block comments is apparent.

There are other options. We could borrow code and /code from HTML
to have code and non-code regions. (In Java, where HTML is allowed in
the doc comments, I wanted my editor to toggle between HTML editing
and code editing. Not all wishes get fulfilled.)

I'd like to hear from people who use Python's multi-line strings other
than in doc comments.

 What would you have to say about a language which
 had no specialised comment syntax whatsoever, and expected
 you to use semantically irrelevent string literals?

I'd say the language predated Fortran, which means Amazing Grace
Hopper wrote it. Perhaps A-0 didn't have comments?
-- 
http://mail.python.org/mailman/listinfo/python-list


Searching for Happiness ?

2007-12-18 Thread aassime abdellatif
Searching for Happiness ?



Dr. Saleh Abdul Azeez As Sindee


 Happiness is a common goal that everyone strives to attain.
Philosophers, intellectuals, doctors and artists alike have all
strived in search of the causes of happiness and ways to escape
anxiety.

The reality is, however, that the proposed solutions achieve only
partial or superficial happiness. They are more or less like drugs
which only provide temporary relief; when their effect wares off,
anxieties return two fold.

The following words invite you to ultimate happiness and will lead you
to true success. But before you begin reading, I hope that you to take
a moment to try to open your heart and mind - as the intelligent one
is he who searches for the truth no matter where it lies.

An undeniable reality is that permanent happiness cannot be achieved
except by believing in God - The Creator - and following His guidance.
Since it is He who created mankind, He is the one who knows what
pleases and benefits them, just as he knows what saddens and harms
them. A number of psychologists have affirmed that only a religious
person lives with true content and serenity. So if believing in God
leads to ultimate happiness, then how can this be achieved?

There are numerous religions and a variety of creeds. However, their
critical differences in core issues make it impossible for all of them
to be correct. So which is the correct religion? What is the correct
creed that God requires us to believe in and in the end pleases Him?
And which one of these creeds guarantees us happiness in this life and
in the hereafter?

Before answering these questions, a criterion must first be
established to be used as a basis for correctly determining the true
religion. I firmly believe that all sensible people will agree that a
religion is not deemed correct simply due to the fact that one was
raised in that religion, had parents that adhered to it, or lived in a
society that practiced it. Rather a religion's accuracy and
authenticity are based upon substantial evidence and firm intellectual
proofs. Intellect, the distinguishing factor between mankind and
animals, must be applied when studying the issue of religion, which is
undeniably the most important and gravest of all matters.

A short journey into the world of religions and sifting through
various creeds could prove to be a good method in arriving at the
desired conclusion. In order to save you the time and effort, I say
with full conviction and confidence that no matter how much you
investigate this issue, you will only arrive at one reality: that the
true and correct religion is Islam and that true happiness and content
lies within it.

Before you hastily rebut this statement and stop reading, please
realize that completing the rest would not harm you at all, and it may
in fact benefit you. Also, remember that you have an intellect by
which you can distinguish things and determine truth from falsehood.

Why Islam?

This is an important question, indicating that the questioner is
mature and enlightened. In response I say:

Islam is a religion that includes a number of merits and
characteristics that are absent from other religions. These
characteristics, alone, serve as convincing evidence that Islam is the
true religion of God. You can determine the authenticity of this
statement by contemplating them.

Islam's many merits and characteristics make it impossible to
elaborate on all of them. However, some of the most important can be
summarized as follows:

1. Amongst the greatest merits of Islam is that it fulfills the
spiritual aspects of the human being and enables those who embrace it
to have an ongoing connection with God. This makes it possible for
them to be at ease spiritually. It shields them from chaos, being lost
or feeling (spiritually) empty, and protects from mental instability.

2. Another of Islam's merits is that it coincides totally with common
sense. All of the Islamic legislation and its rulings are acceptable
intellectually and are never contradictory. One man who embraced Islam
was asked why he did so and replied, Islam never ordered me to do
anything that I later wished wasn't obligated, and it never forbade me
from anything that I later wished wasn't forbidden.
Much of what is readily accepted in other religions causes great
confusion. This confusion makes it difficult to believe many of the
fundamental tenets/doctrines that these religions are based upon. On
the other hand, we find that Islam respects the intellect, prohibits
ignorance, and condemns blind following.

3. Islam is an all-inclusive way of life attending to both spiritual
and physical needs. Practicing Islam does not mean that one has to be
secluded or that he is prohibited from the finer things in life.
Rather, according to Islam, a person can be religious and still enjoy
a normal life - attaining prestigious ranks/positions and achieving
the highest academic degrees.

4. Among the merits of Islam is that it is a 

Re: checking a string against multiple patterns

2007-12-18 Thread Duncan Booth
tomasz [EMAIL PROTECTED] wrote:

 Is there an alternative to it? Am I missing something? Python doesn't
 have special variables $1, $2 (right?) so you must assign the result
 of a match to a variable, to be able to access the groups.

Look for repetition in your code and remove it. That will almost always 
remove the nesting. Or, combine your regular expressions into one large 
expression and branch on the existence of relevant groups. Using named 
groups stops all your code breaking just because you need to change one 
part of the regex.

e.g. This would handle your example, but it is just one way to do it:

import re
from string import Template

def sub(patterns, s):
for pat, repl in patterns:
m = re.match(pat, s)
if m:
return Template(repl).substitute(m.groupdict())
return s

PATTERNS = [
(r'(?Pstart.*?)(?Pbb+)', 'start=$start, b=$b'),
(r'(?Paa+)(?Ptail.*)$', 'Got a: $a, tail=$tail'),
(r'(?Pcc+)', 'starts with c: $c'),
]

 sub(PATTERNS, 'abc')
'start=a, b=b'
 sub(PATTERNS, 'is a something')
'is a something'
 sub(PATTERNS, 'a something')
'Got a: a, tail= something'

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


Re: Debugging pipe IPC

2007-12-18 Thread Jim B. Wilson
Ian Clark wrote:

 ... whatever 'mother' was sending it (Clean your room! most like)

:)

 If it's very verbose ...

Alas, it is quite verbose.  Constructing a single instance of a class
(from the Pyrex extension acting as the child's two-way radio) could
involve tens of thousands of more-or-less random exchanges between
mother and child.  A subsequent method call could trigger a similar
volume of traffic.

And it isn't this communication I'm worried about.  All that seems to go
quite well.  My fondest wish is to play the role of the child at the
good old  prompt.  Such play would allow me to test tiny snippets
of code that I could later incorporate into an actual child.

My wish may not be possible.  If so, it's no great tragedy.  A simple
test goes from:

 foo = askmommy()
 foo.why()

to:

   1. Typing similar statements into my editor.
   2. Saving these statements to a file, say test.py.
   3. Making clicky-clicky in the mother application to run test.py.
   4. Noticing that nothing appears on my terminal.
   5. Inserting sys.stderr, into print foo.why() :)
   6. Repeating steps 2 and 3.

Steps 4, 5 and 6 are required because the mother has absolutely no
compunction against infanticide when her child asks her a question she
cannot answer.

If my wish isn't possible, it will be the first time.  Normally, when I
wonder if Python can do something, I imagine what the syntax would be if
it could, type it in, and sure enough it works.

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


Best idiom to unpack a variable-size sequence

2007-12-18 Thread ram
Here's a little issue I run into more than I like: I often need to
unpack a sequence that may be too short or too long into a fixed-size
set of items:

a, b, c = seq  # when seq = (1, 2, 3, 4, ...) or seq = (1, 2)

What I usually do is something like this:

 a, b, c = (list(seq) + [None, None, None])[:3]

but that just feels rather ugly to me -- is there a good Pythonic
idiom for this?

Thx,
Rick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to protect my new commercial software.

2007-12-18 Thread Jon Ribbens
On 2007-12-18, Grant Edwards [EMAIL PROTECTED] wrote:
 On 2007-12-18, Jan Claeys [EMAIL PROTECTED] wrote:
 No, it's only copyrighted when you _publish_ it.

 Interesting.  So, in Europe, if somebody steals something you
 wrote before you get it published, they're free to do with it
 as they please?

No, I believe the above comment is false. The Berne Convention of 1887
makes copyright automatic as soon as a work is written or recorded.
Thus, most of Europe has had automatic copyright for a very long time,
and all of it does now.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OpenOpt install

2007-12-18 Thread dmitrey
thank you, I'll try to fix the issue when I'll have more time, I'm
short of the one for now because of some other urgent work.
D.

On Dec 18, 10:53 am, Robert Kern [EMAIL PROTECTED] wrote:
 dmitrey wrote:
  When earlier OpenOpt versions had been installed there were no
  compiled pyc-files (in destination directory). I called to mailing
  list but no obvious receipt had been achieved. Matthieu had done some
  changes but it yielded other mistakes (no some py-files detected or
  kind of), so I had removed those changes and write my own, for to have
  OO py-files being compiled when installed, because next time when they
  will be run user may not have root permissions, so he will recompile
  source files each time OO starts.

 Well, the problem there is that you have put code into subdirectories that
 aren't packages. Then you manually add the directories to sys.path when you
 import scikits.openopt.oo . This is a bad thing to do for several reasons; one
 reason is that you don't get the correct .pyc files.

 You need to make the directory structure match the package structure. For
 example, you currently have the module scikits.openopt.LP in
 scikits/openopt/Kernel/LP/LP.py . You have two options:

   * you can make the directory structure match the package structure by moving
 the files to the correct location:

 $ mv scikits/openopt/Kernel/LP/LP.py scikits/openopt/LP.py

   * you can make the package structure match the directory structure by adding
 __init__.py files to the subdirectories and changing the imports to match:

 $ touch scikits/openopt/Kernel/__init__.py
 $ touch scikits/openopt/Kernel/LP/__init__.py
 $ vim scikits/openopt/oo.py
   # 1. Delete the sys.path munging.
   # 2. Change from LP import LP as CLP to from Kernel.LP import LP as 
 CLP

 --
 Robert Kern

 I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth.
   -- Umberto Eco

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


Changing intobject to use int rather than long

2007-12-18 Thread Clarence
Does anyone think (or know) that it might cause any internal problems
if the ival member of the struct defining an intobject were to be
changed from its current long int to just int?

When you move your application to a 64-bit system in order to get a
bigger address space to store your millions/billions of integers in
RAM, but they get twice as big, you don't gain very much.

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


Re: Best idiom to unpack a variable-size sequence

2007-12-18 Thread George Sakkis
On Dec 18, 12:49 pm, ram [EMAIL PROTECTED] wrote:
 Here's a little issue I run into more than I like: I often need to
 unpack a sequence that may be too short or too long into a fixed-size
 set of items:

 a, b, c = seq  # when seq = (1, 2, 3, 4, ...) or seq = (1, 2)

 What I usually do is something like this:

  a, b, c = (list(seq) + [None, None, None])[:3]

 but that just feels rather ugly to me -- is there a good Pythonic
 idiom for this?

In terms of brevity I don't think so; however it can be done more
efficient and general (e.g. for infinite series) using itertools:

from itertools import islice, chain, repeat

def unpack(iterable, n, default=None):
return islice(chain(iterable,repeat(default)), n)

a, b, c = unpack(seq, 3)

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


Re: Best idiom to unpack a variable-size sequence

2007-12-18 Thread Duncan Booth
ram [EMAIL PROTECTED] wrote:

 Here's a little issue I run into more than I like: I often need to
 unpack a sequence that may be too short or too long into a fixed-size
 set of items:
 
 a, b, c = seq  # when seq = (1, 2, 3, 4, ...) or seq = (1, 2)
 
 What I usually do is something like this:
 
  a, b, c = (list(seq) + [None, None, None])[:3]
 
 but that just feels rather ugly to me -- is there a good Pythonic
 idiom for this?

Pythonic might be to be explicit: i.e. know in advance how long the 
sequence actually is.

One drawback I see with your code is that it doesn't give you any way to 
specify different defaults for the values. So here's an alternative to 
consider: try passing your sequence to a function. This lets you specify 
appropriate defaults, and it reads quite cleanly. Of course it also forces 
you to extract the code using those variables out into a separate function, 
but that may not be a bad thing.

 def process(a=None, b=None, c=None):
print a, b, c


 seq = iter('abcd')
 process(*itertools.islice(seq,0,3))
a b c
 seq = iter('ab')
 process(*itertools.islice(seq,0,3))
a b None
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lotus nsf to mbox

2007-12-18 Thread Fabian Braennstroem
Hi to all,

thanks, I'll try your suggestions...

Regards!
Fabian

Brian Munroe schrieb am 12/15/2007 07:10 PM:
 On Dec 15, 11:04 am, Fabian Braennstroem [EMAIL PROTECTED]
 wrote:
 
 thanks for your ideas! I actually thought of something like
 a python parser, which just converts the nsf structure to an
 mbox; could that work!?

 
 Well, If you wish to go that route, I believe you will have to reverse
 engineer the Notes Database binary structure because I've never seen
 it published anywhere.  My suggestion, if you can use a Windows
 machine, just use the Lotus Notes COM Objects via the Python Win32
 bindings, as mentioned above.
 
 If you really need to do it from Linux and are lucky enough to be
 running the IIOP task on your Domino server, then you could possibly
 use CORBA.
 

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


Re: Changing intobject to use int rather than long

2007-12-18 Thread Chris Mellon
On Dec 18, 2007 11:59 AM, Clarence [EMAIL PROTECTED] wrote:
 Does anyone think (or know) that it might cause any internal problems
 if the ival member of the struct defining an intobject were to be
 changed from its current long int to just int?

 When you move your application to a 64-bit system in order to get a
 bigger address space to store your millions/billions of integers in
 RAM, but they get twice as big, you don't gain very much.


Your int objects get twice as large, but you get 4294967296 times more
address space.

(They don't always get twice as large, and you don't actually get that
much address space, and there's lots of other things wrong with this
answer, but the core truth - that your available address space grows
at a greater rate than the size of your ints - is correct).

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

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


Re: Changing intobject to use int rather than long

2007-12-18 Thread Clarence
On Dec 18, 6:24 pm, Chris Mellon [EMAIL PROTECTED] wrote:

 Your int objects get twice as large, but you get 4294967296 times more
 address space.

 (They don't always get twice as large, and you don't actually get that
 much address space, and there's lots of other things wrong with this
 answer, but the core truth - that your available address space grows
 at a greater rate than the size of your ints - is correct).

Technically true, but in my real world, I deal with physical RAM in
the machine. I went from a 2GB machine that was using half its memory
to an 8GB machine that is using one quarter its memory. Yes, it's
better,
but I still want that factor of two!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to protect my new commercial software.

2007-12-18 Thread tinnews
Jan Claeys [EMAIL PROTECTED] wrote:
 Op Fri, 14 Dec 2007 16:54:35 +, schreef Grant Edwards:
 
  Uh what?  I don't know what country you're in, but in the US, it doesn't
  take any time at all to copyright something.  The mere act of writing
  something copyrights it.  I thought it was the same in Europe as well.
 
 No, it's only copyrighted when you _publish_ it.
 
Which basically means letting anyone else see it, i.e. sending as an
E-Mail, posting on Usenet, etc.


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


why only an msi-installer for windows ?

2007-12-18 Thread Stef Mientki
hello,

having a lot of trouble installing 2.5 (without affecting my stable 2.4),
I wonder why there's only a msi installer for windows users ?

thanks,
Stef
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: .NET and Python Integration Problem and PDF Library (Need Help and Suggestions)

2007-12-18 Thread Joshua Kugler
Ravi Kumar wrote:
 - your opinion with available PDF Libraries, that are best among. Also
 which library to use for Windows server platform (there is limitation
 on installing long chain libraries that include other deep
 dependencies too). A pure python PDF library would be good, but which
 one.
 -Which XML Library is pure python based.

Never done Python/.NET integration, so I can't help you there.

PDF library: ReportLab. But that is most generation of PDFs.  For reading,
splitting, etc, you may have to look at their commercial offering.  And I
do believe it is all pure python.

XML: ElementTree  http://effbot.org/zone/element-index.htm  Should be all
you need.

Hope that helps some.

j

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


Re: Changing intobject to use int rather than long

2007-12-18 Thread Hrvoje Niksic
Clarence [EMAIL PROTECTED] writes:

 When you move your application to a 64-bit system in order to get a
 bigger address space to store your millions/billions of integers in
 RAM, but they get twice as big, you don't gain very much.

I don't think changing the underlying type will help at all.  The
layout of the int object is as follows:

typedef struct {
// PyObject_HEAD
Py_ssize_t ob_refcnt;
struct _typeobject *ob_type;
// the actual value
long ob_ival;
} PyIntObject;

On a 64-bit machine, that's 16 bytes for PyObject_HEAD and 8 more
bytes for the value, 24 bytes total.  Changing long to int won't
decrease the struct size to 20 because the compiler will pad it to 24,
the nearest multiple of 8.  (Forcing the compiler to pack the struct
won't help because malloc will still pad it for you.)

If you need to store millions of integers compactly, maybe
array.array('i') can help.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New+old-style multiple inheritance

2007-12-18 Thread Jonathan Gardner
On Dec 18, 7:08 am, [EMAIL PROTECTED]
[EMAIL PROTECTED] wrote:
 We are trying to monkey-patch a third-party library that mixes new and
 old-style classes with multiple inheritance.  In so doing we have
 uncovered some unexpected behaviour:

snip

 I know this level of messing with python internals is a bit risky but
 I'm wondering why the above code doesn't work.


You've already discovered why--you're mixing old and new style
classes.

Monkey patching is definitely unpythonic. You must be a Ruby guy. Why
don't you try doing something else to get the behavior you want,
something more explicit?

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


Re: Debugging pipe IPC

2007-12-18 Thread Ian Clark
Jim B. Wilson wrote:
 ...  My fondest wish is to play the role of the child at the
 good old  prompt. ...
 
 Jim

Okay, I misunderstood the direction you wanted to go. I thought that you 
wanted to play the part of the mother, giving commands to the child and 
not the other way around.

Assuming you're on a *nix make child.py as:

import os
os.system(netcat -l -p 1234 localhost)

Run it though mother and on another terminal type: netcat localhost 1234

HTH,

Ian

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


Re: WikiInclude on 0.11 - Noah Kantrowitz blocks bug-fix

2007-12-18 Thread smallpond
On Dec 17, 9:23 pm, Ilias Lazaridis [EMAIL PROTECTED] wrote:
 Essence:

  * Deletion of valid defect reports on trac community resources

 The WikiInclude plugin is not recognised on trac 0.11, thus I took a
 look an made a small addition to the setup.py (the entry_point).

 Other users have the same problem, thus I filed a ticket in the trac-
 hacks community resource.

 Mr. Noah Kantrowitz closed the ticket as invalid. My comments within
 this ticket are deleted, directly in the database, which is the same
 as censorship. I've copied the email-notification from my comment
 below. [1]

 Please realize:

  * this is a real-live defect, which remains unprocessed, thus more
 users run into this trouble.
  * My attemps to inform users in the user-threads do not show up in
 all threads (moderation on trac-users!!!)
  * The IncludeMacro is not compatible to the WikiInclude macro
  * My comments were deleted in a non-trackable way
  * Users of the WikiInclude plugin are not informed in any way

 You are may wondering why the trac project fails to produce a stable
 1.0 version since years. The answer is here:

 http://case.lazaridis.com/wiki/TracAudit

 -

 [1]

 #2294: Plugin is not detectd on trac 0.11 (even the 0.11 specific one)
 
 +---
 Reporter:  [EMAIL PROTECTED]  |Owner:  yu-ji
Type:  defect   |   Status:  reopened
 Priority:  normal   |Component:  WikiIncludePlugin
 Severity:  critical |   Resolution:
 Keywords:   |  Release:  0.11
 
 +---
 Changes (by [EMAIL PROTECTED]):

  * status:  closed = reopened
  * resolution:  invalid =
  * summary:  Missing entry_point within setup.py = Plugin is not
  detectd on trac 0.11 (even the 0.11 specific
  one)

 Comment:

  (Mr. Kantrowitz. This is defenitely a defect, which occoured for
 several
  users. The provided information helps any user which hits on this
 ticket
  via a search. I ask you once more to stop with the deletions on this
  '''community''' resource).

  The resolution invalid is incorrect.

  The problem exists for me '''and other''' users, see e.g.:

  * [http://groups.google.com/group/trac-users/browse_frm/thread/
 de454e7dcf9f0438/d9806ad4a31a14a7 thread 1]
  * [http://groups.google.com/group/trac-users/browse_frm/thread/
 2ccf4b2855a6f242?q=WikiInclude thread 2]

  I've solved it whilst simply adding the entry point to the setup.py.

  It is ok to point to the more flexible and maintained IncludeMacro,
 but
  other people possibly just want to continue to use the simpler
  WikiInclude one.

  I suggest the maintainer of WikiInclude (or another developer)
 corrects
  the setup.py in the repo, and additionally one should place a note in
 the
  WikiInclude documentation, that there's a more flexible
 IncludeMacro
  available.


Trac is a python application.
Please read the posting guidelines for c.l.p.m
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Changing intobject to use int rather than long

2007-12-18 Thread Clarence
On Dec 18, 6:58 pm, Hrvoje Niksic [EMAIL PROTECTED] wrote:

 I don't think changing the underlying type will help at all.  The


 On a 64-bit machine, that's 16 bytes for PyObject_HEAD and 8 more
 bytes for the value, 24 bytes total.  Changing long to int won't
 decrease the struct size to 20 because the compiler will pad it to 24,
 the nearest multiple of 8.  (Forcing the compiler to pack the struct
 won't help because malloc will still pad it for you.)

That's an excellent point. And true, too. Thanks, that will lay the
issue
to rest.

 If you need to store millions of integers compactly, maybe
 array.array('i') can help.

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


Re: Does fileinput.input() read STDIN all at once?

2007-12-18 Thread Jonathan Gardner
On Dec 18, 5:55 am, Adam Funk [EMAIL PROTECTED] wrote:
 I'm using this sort of standard thing:

for line in fileinput.input():
   do_stuff(line)

 and wondering whether it reads until it hits an EOF and then passes
 lines (one at a time) into the variable line.  This appears to be the
 behaviour when it's reading STDIN interactively (i.e. from the
 keyboard).

 As a test, I tried this:

for line in fileinput.input():
   print '**', line

 and found that it would print nothing until I hit Ctl-D, then print
 all the lines, then wait for another Ctl-D, and so on (until I pressed
 Ctl-D twice in succession to end the loop).


There is probably a 1024 byte buffer. Try filling it up and see if you
get something before you hit CTRL-D.

Otherwise, the writers have to flush the buffer if they want a line to
be sent before the buffer fills up. C++ endl would do this, I believe,
in addition to printing '\n'.

Note that terminals (what you get if you are typing from the command
line) are terminals and behave quite differently than open files.

 Is it possible to configure this to pass each line of input into line
 as it comes?


It's up to the writer to flush the buffers. There's not much you can
do, so just learn to live with it.

It sounds like you want to write some kind of interactive program for
the terminal. Do yourself a favor and use curses or go with a full-
blown GUI.
-- 
http://mail.python.org/mailman/listinfo/python-list


Why custom objects take so much memory?

2007-12-18 Thread jsanshef
Hi,

after a couple of days of script debugging, I kind of found that some
assumptions I was doing about the memory complexity of my classes are
not true. I decided to do a simple script to isolate the problem:

class MyClass:
def __init__(self,s):
self.mystring  = s

mylist = []
for i in range(1024*1024):
mylist.append(MyClass(str(i))) #allocation
#stage 1
mylist = None
gc.collect()
#stage 2

I take measures of the memory consumption of the script at #stage1 and
#stage 2 and I obtain:
#stage1 - 238MB
#stage2 - 15MB

That means every object is around 223 bytes in size That's too
much considering it only contains a string with a maximum size of 7
chars.

If you change the allocation line for this other:
mylist.append(str(i)) #we don't create the custom class, but append the 
string directly into the list

the numbers decrease substantially to:
#stage1 - 47.6MB
#stage2 - 15MB
(so this time we can say string vars occupy around 32 bytesstill a
lot, isn't it?)

So, what's exactly going on behind the scenes? Why is using custom
objects SO expensive? What other ways of creating structures can be
used (cheaper in memory usage)?

Thanks a lot in advance!



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


Re: checking a string against multiple patterns

2007-12-18 Thread Jonathan Gardner
On Dec 18, 4:41 am, tomasz [EMAIL PROTECTED] wrote:
 Is there an alternative to it? Am I missing something? Python doesn't
 have special variables $1, $2 (right?) so you must assign the result
 of a match to a variable, to be able to access the groups.

 I'd appreciate any hints.


Don't use regexes for something as simple as this. Try find().

Most of the time I use regexes in perl (90%+) I am doing something
that can be done much better using the string methods and some simple
operations. Plus, it turns out to be faster than perl usually.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Changing intobject to use int rather than long

2007-12-18 Thread Terry Reedy

Clarence [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
| That's an excellent point. And true, too. Thanks, that will lay the
| issue to rest.

Good idea.  I think people who moved to 64 bits to get 64 bits would be 
upset if they did not ;-).





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


Re: is it possible to install 2 Python versions on windows XP ?

2007-12-18 Thread Stef Mientki
I finally found a way to let everything work:


My base system is a stable Scipy installation, based on Python 2.4,
with a few extra or updated libraries.
This Python installation is completed with RPYC and PyScripter,
to form a good workplace to develop GUI through wxPython.

Installing of a working Python 2.5 version is done in the following way:
- get a winXP system on which Python is not necessary
- install on that PC Python 2.5
- copy from windows\system32\Python25.dll
   to  the root where you installed Python 2.5
- now you can move the newly created root map to any place you like
- place a shortcut to python.exe on your desktop
- drop any file you like to run in Python 2.5 on the shortcut

Seems to work like a charm.
But maybe there might be better ways.

cheers,
Stef
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New+old-style multiple inheritance

2007-12-18 Thread Gabriel Genellina
On 18 dic, 12:08, [EMAIL PROTECTED]
[EMAIL PROTECTED] wrote:

 We are trying to monkey-patch a third-party library that mixes new and
 old-style classes with multiple inheritance.  In so doing we have
 uncovered some unexpected behaviour:

 quote
 class Foo:
 pass

 class Bar(object):
 pass

 class Baz(Foo,Bar):
 pass

 # Monkey-patch Foo to add a special method
 def my_nonzero(self):
 print my_nonzero called
 return False
 Foo.__nonzero__ = my_nonzero

 b = Baz()

 print doing the test on Baz(Foo,Bar).  Should return false
 if b:
 print true
 else:
 print false
 /quote

 Produces this output:

   doing the test on Baz(Foo,Bar).  Should return false
   true

 With some experimentation it is clear that this behaviour only occurs
 when you combine new+old-style multiple inheritance, monkey-patching
 and special methods.  If Foo and Bar are either old or new-style it
 works.  calling b.__nonzero__() directly works.  Defining __nonzero__
 within Foo works.

 I know this level of messing with python internals is a bit risky but
 I'm wondering why the above code doesn't work.

I think I can barely explain what happens here (but I may be
absolutely wrong! Please someone with greater knowledge of Python
innards correct whatever is wrong on my description!)

type objects contain slots (function pointers) corresponding to the
magic methods like __nonzero__ (this one is stored into the
nb_nonzero slot). new-style classes are types; old-style classes are
not (they're all instances of classobj).
The slots are populated when a new type is created (e.g., when
creating a new-style class) and are updated when a magic attribute is
set onto the type. By example, setting the __nonzero__ attribute on a
new-style class updates the nb_nonzero slot. old-style classes just
store the magic attribute in its __dict__. Note that if you patch Foo
*before* defining Baz, it works fine, because Baz sees the magic
attribute and can populate its nb_nonzero slot when the new type is
created.

When you define Baz, neither Foo nor Bar have a __nonzero__ at this
time, so the nb_nonzero slot on Baz is empty.
Later, when you alter Foo, Baz cannot notice it (Foo has no way to
notify Baz that something changed).

If Foo were a new-style class, things are different: new-style classes
maintain a list of subclasses, and the subclasses can then be notified
of changes. In particular, setting a magic attribute on a base class
notifies all its subclasses, and the corresponding slots are updated.

The problem seems to be exactly that: old-style base classes can't
notify its derived new-style classes when magic methods are added, so
the corresponding slots aren't updated. Always asking the base class
whether it has a magic method or not would slow down all method
lookups.

To force a slot update:

py Baz.__nonzero__ = xxx
py del Baz.__nonzero__
py bool(b)
my_nonzero called
False

(setting or deleting __nonzero__ triggers the slot update)

This is *why* it happens. How to avoid this... well, don't do that in
the first place :) Or try to patch the base class *before* the new-
style derived class is defined. Or replace the derived class with a
new version of itself (once the base was patched). Or, if you know all
the derived classes, force a slot update on them as above.

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


Funny python cartoon... hope it's not a repost

2007-12-18 Thread Breal
http://xkcd.com/353/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another newbie design question

2007-12-18 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
 Fortran (1957) had line comments. C (1972) replaced these with non-
 nested block comments. C++ (1983) added here-to-EOL comments. Python
 (1991) keeps here-to-EOL comments but replaces block comments with
 multi-line quotes. Block comments and multi-line quotes both serve the
 same purpose as doc comments. Block comments, especially if they nest,
 are helpful for commenting out code. Multi-line quotes serve to add
 text.
 
 Is Python, in this particular, an advance over C++?
 
 I wrote a lot of Java (here-to-EOL and block comments) without ever
 feeling the need for multi-line quotes.

I wrote a lot of Java without ever feeling the need for things functions 
as objects, lexical closures, lazy evaluation, anonymous functions etc. 
Then I learned to use these features and couldn't stand coding in Java 
no more.

 I've written a little Perl and
 found multi-line quotes useful for responding to -help switches. On
 the other hand -help switches are very old-fashioned, a direction I'll
 not be pointing my tiny beginner's language.

old-fashioned ? Do you have something better to suggest ? Please keep 
in mind that most servers don't have GUIs (for obvious reasons).

But multiline strings are not only useful for old-fashioned -help 
switches - they are useful anywhere you need a quick and simple text 
templating system - be it html, javascript, SQL, whatever - and using a 
full blown templating system would be overkill. IOW, like a lot of other 
features, it's not that you cannot do without, but it really helps when 
it's available *and* braindead easy to setup and use.

My 2 cents...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another newbie design question

2007-12-18 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
(snip)
 I'd like to hear from people who use Python's multi-line strings other
 than in doc comments.

Then: do you hear me ?-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Funny python cartoon... hope it's not a repost

2007-12-18 Thread Bruno Desthuilliers
Breal a écrit :
 http://xkcd.com/353/

Bad luck: it *is* a repost.

While we're at it, did you notice the alternate text for the image ?-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why only an msi-installer for windows ?

2007-12-18 Thread Tim Couper
I think as msi is The *Windows Installer* .. is an engine for the 
installation, maintenance, and removal of software on modern Microsoft 
Windows http://en.wikipedia.org/wiki/Microsoft_Windows systems (from 
Wikipaedia), it's clear it's a Windows product ... not sure that 
they're up for putting it on other operating systems .. but you may want 
to email Bill G and ask him ..

Tim

Stef Mientki wrote:
 hello,

 having a lot of trouble installing 2.5 (without affecting my stable 2.4),
 I wonder why there's only a msi installer for windows users ?

 thanks,
 Stef
   
-- 
http://mail.python.org/mailman/listinfo/python-list


Newbie observations

2007-12-18 Thread MartinRinehart
Warning! Complaints coming.

The good news is that 10-days of part-time Python coding has convinced
me that I picked the right language. Now, observations.

First, it is absolutely horrible being a newbie. I'd forgot how bad it
was. In addition to making a fool of yourself in public, you have to
look up everything. I wanted to find a substring in a string. OK,
Python's a serious computer language, so you know it's got a function
to do this. But where? Look it up in the function reference. OK,
where's the function reference? A line of code that you'd type in a
second is a ten-minute search. Thank God for google.

Second, would anyone mind if we tossed the semi-colon (which this
newbie is forever forgetting)? I think the language is parsable
without it.

Third, could our classes be a little more selfless? Or a lot more
selfless? The Stroustrup's idea of having the compiler, not the
programmer, worry about the self pointer was an excellent decision.
What was van Rossum thinking?

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


Re: Rounding

2007-12-18 Thread Ron Provost
Adding 0.5, then converting to an int always works for me.

 x = 6.345
 int( x + 0.5 )
 6

Ron


- Original Message - 
From: katie smith [EMAIL PROTECTED]
To: python-list@python.org
Sent: Saturday, December 15, 2007 9:09 AM
Subject: Rounding


 if i have a number 6.345 and i wanted it to be 6 without subtracting .345 
 because it won't always be .345 what do i do?

 how do i round to the nearest whole number. Or in this case round down. Is 
 there an easy way to round down to the nearest whole number?


 
 
 Never miss a thing.  Make Yahoo your home page.
 http://www.yahoo.com/r/hs

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

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


Re: Passing arguments to exe

2007-12-18 Thread kyosohma
On Dec 15, 6:46 pm, Dennis Lee Bieber [EMAIL PROTECTED] wrote:
 On Fri, 14 Dec 2007 16:38:28 -0800 (PST), [EMAIL PROTECTED] declaimed
 the following in comp.lang.python:

  The executable runs, but no argument appears to get passed into it. Of
  course, I don't really know that for sure as the executable doesn't
  redirect stdout/stderr. I tried doing something like this in the above
  reg entry:

  cmd /C c:\program files\myProg.exe %1
  c:\program files\myProg.exe %1
  c:\program files\myProg.exe

 What happens if you put the %1 OUTSIDE the quotes...

 cmd /c c:\program files\myProg.exe %1

 After all, if the quotes are being used to keep the command line seeing
 program files as a single term in the path, then your quotes are also
 treating myProg.exe %1 as a single term.
 --
 WulfraedDennis Lee Bieber   KD6MOG
 [EMAIL PROTECTED] [EMAIL PROTECTED]
 HTTP://wlfraed.home.netcom.com/
 (Bestiaria Support Staff:   [EMAIL PROTECTED])
 HTTP://www.bestiaria.com/

This works:

c:\program files\myProg.exe %1

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


Re: Why custom objects take so much memory?

2007-12-18 Thread Chris Mellon
On Dec 18, 2007 1:26 PM, jsanshef [EMAIL PROTECTED] wrote:
 Hi,

 after a couple of days of script debugging, I kind of found that some
 assumptions I was doing about the memory complexity of my classes are
 not true. I decided to do a simple script to isolate the problem:

 class MyClass:
 def __init__(self,s):
 self.mystring  = s

 mylist = []
 for i in range(1024*1024):
 mylist.append(MyClass(str(i))) #allocation
 #stage 1
 mylist = None
 gc.collect()
 #stage 2

 I take measures of the memory consumption of the script at #stage1 and
 #stage 2 and I obtain:
 #stage1 - 238MB
 #stage2 - 15MB

 That means every object is around 223 bytes in size That's too
 much considering it only contains a string with a maximum size of 7
 chars.


Classes are fairly heavyweight - in your case you've got the size of
the PyObject struct, a dictionary for class attributes (which itself
is another pyobject), and the string object (yet another pyobject),
and the actual string data.

 If you change the allocation line for this other:
 mylist.append(str(i)) #we don't create the custom class, but append the 
 string directly into the list

 the numbers decrease substantially to:
 #stage1 - 47.6MB
 #stage2 - 15MB
 (so this time we can say string vars occupy around 32 bytesstill a
 lot, isn't it?)


string objects don't have dictionaries and are smaller than regular
python objects.

 So, what's exactly going on behind the scenes? Why is using custom
 objects SO expensive? What other ways of creating structures can be
 used (cheaper in memory usage)?


If you're worried about per-instance memory costs Python is probably
not the language for your purposes. On the other hand, odds are that
you actually don't need to worry so much.

You can reduce the size of new-style classes (inherit from object) by
quite a bit if you use __slots__ to eliminate the class dictionary.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New+old-style multiple inheritance

2007-12-18 Thread Carl Banks
On Dec 18, 10:08 am, [EMAIL PROTECTED]
[EMAIL PROTECTED] wrote:
 We are trying to monkey-patch a third-party library that mixes new and
 old-style classes with multiple inheritance.

New library?  Geez, if people are dumb enough to do this, are you sure
you want your application to depend on their library?

Sometimes you have to work with code that's not up to your standards,
but come on.


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


Re: Why custom objects take so much memory?

2007-12-18 Thread Hrvoje Niksic
jsanshef [EMAIL PROTECTED] writes:

 That means every object is around 223 bytes in size That's too
 much considering it only contains a string with a maximum size of 7
 chars.

The list itself consumes 4 MB because it stores 1 million PyObject
pointers.  It possibly consumes more due to overallocation, but let's
ignore that.

Each object takes 36 bytes itself: 4 bytes refcount + 4 bytes type ptr
+ 4 bytes dict ptr + 4 bytes weakptr + 12 bytes gc overhead.  That's
not counting malloc overhead, which should be low since objects aren't
malloced individually.  Each object requires a dict, which consumes
additional 52 bytes of memory (40 bytes for the dict struct plus 12
for gc).  That's 88 bytes per object, not counting malloc overhead.

Then there's string allocation: your average string is 6 chars long;
add to that one additional char for the terminating zero.  The string
struct takes up 20 bytes + string length, rounded to nearest
alignment.  For your average case, that's 27 bytes, rounded (I assume) to 28.
You also allocate 1024*1024 integers which are never freed (they're
kept on a free list), and each of which takes up at least 12 bytes.

All that adds up to 128 bytes per object, dispersed over several
different object types.  It doesn't surprise me that Python is eating
200+ MB of memory.

 So, what's exactly going on behind the scenes? Why is using custom
 objects SO expensive? What other ways of creating structures can be
 used (cheaper in memory usage)?

 Thanks a lot in advance!

Use a new-style class and set __slots__:

class MyClass(object):
__slots__ = 'mystring',
def __init__(self, s):
self.mystring = s

That brings down memory consumption to ~80MB, by cutting down the size
of object instance and removing the dict.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie observations

2007-12-18 Thread John Machin
On Dec 19, 7:14 am, [EMAIL PROTECTED] wrote:
 Warning! Complaints coming.

 The good news is that 10-days of part-time Python coding has convinced
 me that I picked the right language. Now, observations.

 First, it is absolutely horrible being a newbie. I'd forgot how bad it
 was. In addition to making a fool of yourself in public,

[snip]


 Second, would anyone mind if we tossed the semi-colon (which this
 newbie is forever forgetting)? I think the language is parsable
 without it.

Do you mean colon?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New+old-style multiple inheritance

2007-12-18 Thread Carl Banks
On Dec 18, 2:09 pm, Jonathan Gardner
[EMAIL PROTECTED] wrote:
 On Dec 18, 7:08 am, [EMAIL PROTECTED]

 [EMAIL PROTECTED] wrote:
  We are trying to monkey-patch a third-party library that mixes new and
  old-style classes with multiple inheritance.  In so doing we have
  uncovered some unexpected behaviour:

 snip

  I know this level of messing with python internals is a bit risky but
  I'm wondering why the above code doesn't work.

 You've already discovered why--you're mixing old and new style
 classes.

 Monkey patching is definitely unpythonic. You must be a Ruby guy. Why
 don't you try doing something else to get the behavior you want,
 something more explicit?

Time and place.

A well-considered, timely monkey-patch can sometimes save all kinds of
workarounds and other headaches.


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


Re: Newbie observations

2007-12-18 Thread Steven Bethard
[EMAIL PROTECTED] wrote:
 First, it is absolutely horrible being a newbie. I'd forgot how bad it
 was. In addition to making a fool of yourself in public, you have to
 look up everything. I wanted to find a substring in a string. OK,
 Python's a serious computer language, so you know it's got a function
 to do this. But where? Look it up in the function reference. OK,
 where's the function reference? A line of code that you'd type in a
 second is a ten-minute search. Thank God for google.

If you're having trouble with some of Python's basic syntax (like 
slicing), you should go through the tutorial first:

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

It doesn't take too long, and you'll hit slicing by section 3.1.2.

 Second, would anyone mind if we tossed the semi-colon (which this
 newbie is forever forgetting)? I think the language is parsable
 without it.

What are you using them for?  They're only intended to separate two 
simple statements on the same line.  I always use one statement per 
line, so I never see semi-colons.  I highly recommend that you never use 
semi-colons either.

 Third, could our classes be a little more selfless? Or a lot more
 selfless? The Stroustrup's idea of having the compiler, not the
 programmer, worry about the self pointer was an excellent decision.
 What was van Rossum thinking?

http://www.python.org/doc/faq/general/#why-must-self-be-used-explicitly-in-method-definitions-and-calls
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another newbie design question

2007-12-18 Thread MartinRinehart
 My 2 cents...

Thanks for the feedback, Bruno. Seriously thinking about ditching the
block comments and adding multi-line strings. (Block comments are the
last item on my tokenizer's todo list. Multi-line strings would be
easier.)

Beginners will be programming fun things in a GUI environment. Think
games. Brightly colored bouncing balls. Remember Pong? That's a Decaf-
level program.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rounding

2007-12-18 Thread John Machin
On Dec 19, 7:21 am, Ron Provost [EMAIL PROTECTED] wrote:
 Adding 0.5, then converting to an int always works for me.

  x = 6.345
  int( x + 0.5 )
  6

Always?

 x = -6.345
 int(x + 0.5)
-5


I therefore deduce that you have never crossed the equator :-)

Be careful, doing that can be dangerous:
http://catless.ncl.ac.uk/Risks/3.44.html#subj1.1
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lotus nsf to mbox

2007-12-18 Thread Adam Lanier
On Tue, 2007-12-18 at 19:25 +, Fabian Braennstroem wrote:
 Hi to all,
 
 thanks, I'll try your suggestions...
 
 Regards!
 Fabian
 
 Brian Munroe schrieb am 12/15/2007 07:10 PM:
  Well, If you wish to go that route, I believe you will have to reverse
  engineer the Notes Database binary structure because I've never seen
  it published anywhere.  My suggestion, if you can use a Windows
  machine, just use the Lotus Notes COM Objects via the Python Win32
  bindings, as mentioned above.
  
  If you really need to do it from Linux and are lucky enough to be
  running the IIOP task on your Domino server, then you could possibly
  use CORBA.

You could always enable the IMAP interface on the Domino machine and use
imaplib to retrieve the mail via IMAP.

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


Re: why only an msi-installer for windows ?

2007-12-18 Thread John Machin
On Dec 19, 7:11 am, Tim Couper [EMAIL PROTECTED] wrote:
 I think as msi is The *Windows Installer* .. is an engine for the
 installation, maintenance, and removal of software on modern Microsoft
 Windows http://en.wikipedia.org/wiki/Microsoft_Windows systems (from
 Wikipaedia), it's clear it's a Windows product ... not sure that
 they're up for putting it on other operating systems .. but you may want
 to email Bill G and ask him ..


It all depends on context, none of which the OP has supplied, and how
much weight one can attach to the position of only in his sentence.

only a msi installer for windows users could mean Python supplies
only an msi installer [no exe installer, as was the case for earlier
Python versions] for Windows users. This presents difficulties
installing Python 2.5 on antique versions of Windows.

If Tim's interpretation is correct, it would help greatly if the OP
would say explicitly what his platform is and what his real problem
is, instead of asking why a purported solution doesn't exist.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New+old-style multiple inheritance

2007-12-18 Thread [EMAIL PROTECTED]
On Dec 18, 8:25 pm, Carl Banks [EMAIL PROTECTED] wrote:
 On Dec 18, 2:09 pm, Jonathan Gardner



 [EMAIL PROTECTED] wrote:
  On Dec 18, 7:08 am, [EMAIL PROTECTED]

  [EMAIL PROTECTED] wrote:
   We are trying to monkey-patch a third-party library that mixes new and
   old-style classes with multiple inheritance.  In so doing we have
   uncovered some unexpected behaviour:

  snip

   I know this level of messing with python internals is a bit risky but
   I'm wondering why the above code doesn't work.

  You've already discovered why--you're mixing old and new style
  classes.

  Monkey patching is definitely unpythonic. You must be a Ruby guy. Why
  don't you try doing something else to get the behavior you want,
  something more explicit?

 Time and place.

 A well-considered, timely monkey-patch can sometimes save all kinds of
 workarounds and other headaches.

 Carl Banks

Indeed, I chuckled at the idea I was a Ruby programmer.  Of course
it's a bit of a hack but monkey-patching has been common place in the
Zope world for years (maybe Zope3 has rid itself of the problem).

Agreed, mixing new and old-style classes in multiple inheritance is
asking for trouble (although the Guido's essay on the new-style
classes  suggests you can: 
http://www.python.org/download/releases/2.2.3/descrintro/#subclassing).
I won't name and shame the library involved but unfortunately we can't
always pick and choose the tools we work with unless we want to write
(or rewrite) everything ourselves.

Cheers,
Stephen.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New+old-style multiple inheritance

2007-12-18 Thread [EMAIL PROTECTED]
Thank Gabriel,

That sounds exactly right and your work-around provides confirmation.
This code is an expedient solution for us so I expect we'll go with
forcing a slot update.  Hopefully the library concerned is going to
fix the problem in a future release.

Cheers,
Stephen.

On  Dec 18, 7:40 pm, Gabriel Genellina [EMAIL PROTECTED] wrote:
 On 18 dic, 12:08, [EMAIL PROTECTED]



 [EMAIL PROTECTED] wrote:
  We are trying to monkey-patch a third-party library that mixes new and
  old-style classes with multiple inheritance.  In so doing we have
  uncovered some unexpected behaviour:

  quote
  class Foo:
  pass

  class Bar(object):
  pass

  class Baz(Foo,Bar):
  pass

  # Monkey-patch Foo to add a special method
  def my_nonzero(self):
  print my_nonzero called
  return False
  Foo.__nonzero__ = my_nonzero

  b = Baz()

  print doing the test on Baz(Foo,Bar).  Should return false
  if b:
  print true
  else:
  print false
  /quote

  Produces this output:

doing the test on Baz(Foo,Bar).  Should return false
true

  With some experimentation it is clear that this behaviour only occurs
  when you combine new+old-style multiple inheritance, monkey-patching
  and special methods.  If Foo and Bar are either old or new-style it
  works.  calling b.__nonzero__() directly works.  Defining __nonzero__
  within Foo works.

  I know this level of messing with python internals is a bit risky but
  I'm wondering why the above code doesn't work.

 I think I can barely explain what happens here (but I may be
 absolutely wrong! Please someone with greater knowledge of Python
 innards correct whatever is wrong on my description!)

 type objects contain slots (function pointers) corresponding to the
 magic methods like __nonzero__ (this one is stored into the
 nb_nonzero slot). new-style classes are types; old-style classes are
 not (they're all instances of classobj).
 The slots are populated when a new type is created (e.g., when
 creating a new-style class) and are updated when a magic attribute is
 set onto the type. By example, setting the __nonzero__ attribute on a
 new-style class updates the nb_nonzero slot. old-style classes just
 store the magic attribute in its __dict__. Note that if you patch Foo
 *before* defining Baz, it works fine, because Baz sees the magic
 attribute and can populate its nb_nonzero slot when the new type is
 created.

 When you define Baz, neither Foo nor Bar have a __nonzero__ at this
 time, so the nb_nonzero slot on Baz is empty.
 Later, when you alter Foo, Baz cannot notice it (Foo has no way to
 notify Baz that something changed).

 If Foo were a new-style class, things are different: new-style classes
 maintain a list of subclasses, and the subclasses can then be notified
 of changes. In particular, setting a magic attribute on a base class
 notifies all its subclasses, and the corresponding slots are updated.

 The problem seems to be exactly that: old-style base classes can't
 notify its derived new-style classes when magic methods are added, so
 the corresponding slots aren't updated. Always asking the base class
 whether it has a magic method or not would slow down all method
 lookups.

 To force a slot update:

 py Baz.__nonzero__ = xxx
 py del Baz.__nonzero__
 py bool(b)
 my_nonzero called
 False

 (setting or deleting __nonzero__ triggers the slot update)

 This is *why* it happens. How to avoid this... well, don't do that in
 the first place :) Or try to patch the base class *before* the new-
 style derived class is defined. Or replace the derived class with a
 new version of itself (once the base was patched). Or, if you know all
 the derived classes, force a slot update on them as above.

 --
 Gabriel Genellina

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


Re: Funny python cartoon... hope it's not a repost

2007-12-18 Thread Breal
On Dec 18, 11:56 am, Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
 Breal a écrit :

 http://xkcd.com/353/

 Bad luck: it *is* a repost.

 While we're at it, did you notice the alternate text for the image ?-)

Did not notice the alt text... friggin hilarious!!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why only an msi-installer for windows ?

2007-12-18 Thread Gabriel Genellina
On 18 dic, 15:54, Stef Mientki [EMAIL PROTECTED] wrote:

 having a lot of trouble installing 2.5 (without affecting my stable 2.4),
 I wonder why there's only a msi installer for windows users ?

What's your problem? I have five versions installed (2.1, 2.3, 2.4,
2.5 and svn) and they coexist peacefully. Just make sure when
installing 2.5: a) use a different directory (obviously!) b) don't
associate .py extension with this new version.
Regarding the standard library, Python tries to locate it based on
where the executable (python.exe) resides, so this should not be a
problem. Better if you don't set a PYTHONPATH environment variable
(usually there is no need to do that; if required, you can extend the
search path using .pth files instead)

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


Re: Best way to protect my new commercial software.

2007-12-18 Thread Steven D'Aprano
On Tue, 18 Dec 2007 17:04:29 +, Grant Edwards wrote:

 On 2007-12-18, Jan Claeys [EMAIL PROTECTED] wrote:
 Op Fri, 14 Dec 2007 16:54:35 +, schreef Grant Edwards:

 Uh what?  I don't know what country you're in, but in the US, it
 doesn't take any time at all to copyright something.  The mere act of
 writing something copyrights it.  I thought it was the same in Europe
 as well.

 No, it's only copyrighted when you _publish_ it.
 
 Interesting.  So, in Europe, if somebody steals something you wrote
 before you get it published, they're free to do with it as they please?

Please do not conflate theft and copyright infringement, or theft and 
plagiarism. They are very different concepts, and confusing them does not 
help.


 I'm glad it doesn't work that way here in the US.  Over here, something
 is copyrighted as soon as it's written (actually I think the phrase is
 fixed in a medium or something like that).

I'm not glad at all. The Change from an everything is uncopyrighted 
unless explicitly copyrighted model to a everything is copyrighted 
unless explicitly exempted model was only one of many deleterious 
changes to copyright law over the last half century or so.

It means the merest throw-away scribble on a napkin has equal protection 
to the opus an author slaved over for thirty years (although in fairness 
you are unlikely to win a copyright case over the words Meet me at the 
bar scribbled on a napkin then tossed in a rubbish bin... *wink*). It 
means that there is a serious problem of orphan works, where rare and 
valuable films from the 1920s and earlier are rapidly decaying into an 
unusable powder because nobody dares copy them lest the unknown copyright 
owners descend like vultures and sue you for copyright infringement 
*after* you've done the hard work of restoring our cultural heritage.

(Although the orphan works problem is at least equally as much a problem 
of excessively long copyrights as it is to do with automatic copyright.)

I dare say that European countries which have had automatic copyright 
longer than the US have seen far more of their national heritage (early 
film, photographs and the like) rot away.

Discussions of copyright so often focus on protecting the author's 
privileges and ignore the opportunity costs of locking up works. When 
works needed to be explicitly copyrighted, something of the order of just 
ONE PERCENT of authors bothered to copyright their published works -- and 
just one percent of them bothered to renew it for a second 14 year term. 
That gives you an idea of how valuable copyright really is. For every 
Mickey Mouse, there are 100,000 or more works that don't have enough 
economic value to the creator to bother protecting -- but they're part of 
our cultural heritage, and maybe somebody else could build on top of it, 
like Disney built their empire on other folks' uncopyrighted stories and 
ideas. Even Mickey Mouse himself got his start in a derivative work of 
Buster Keaton's Steamboat Bill Jr.

This newsgroup is a perfect example of the fraud that is the idea of 
copyright. Every single post sent to the newsgroup is copyrighted, and 
yet they invariable have no economic value to the author. If they have 
any economic value, it is to the readers -- but they don't pay for it, 
and we authors don't ask for payment. In principle, anyone who forwards 
on something they read here, or uses a code snippet in their own work, is 
infringing copyright. We don't need copyright to encourage us to create 
works of this nature, and in fact this newsgroup can only exist by 
pretending copyright doesn't exist -- there are informal conventions that 
unless somebody explicitly states otherwise, any reader can forward on 
posts, copy and reuse code, and so forth.

(Disclaimer: for the avoidance of all doubt, I'm not suggesting that ALL 
creative works should be uncopyrighted, or that no creative works benefit 
from the encouragement of copyright.)



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


Re: Funny python cartoon... hope it's not a repost

2007-12-18 Thread Ben Finney
Breal [EMAIL PROTECTED] writes:

 http://xkcd.com/353/

Instead of *hoping* it's not a repost, please search the group
archives *before* posting.

-- 
 \ I'm beginning to think that life is just one long Yoko Ono |
  `\   album; no rhyme or reason, just a lot of incoherent shrieks and |
_o__)   then it's over.  -- Ian Wolff |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Strict mode?

2007-12-18 Thread Jack
While enjoying the dynamic feature of Python I find it difficult to refactor 
code without breaking it. For example, if I modify a function to take more 
arguments, or arguments of different types, I'll need to manually find out 
all places where the function is called and make sure I modify them all, 
unlike in C/Java, where the compiler will do the work of checking function 
signatures, etc. I suppose there isn't a strict mode in Python. It would be 
helpful though, when I don't need things to be so dynamic, and this is often 
the case, when it comes to function arguments and return values, for 
example. Even a module level or function level flag would be very helpful to 
find broken code. Or, are there any third party tools that do this? 


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


Don't use __slots__ (was Re: Why custom objects take so much memory?)

2007-12-18 Thread Aahz
In article [EMAIL PROTECTED],
Chris Mellon [EMAIL PROTECTED] wrote:

You can reduce the size of new-style classes (inherit from object) by
quite a bit if you use __slots__ to eliminate the class dictionary.

You can also reduce your functionality quite a bit by using __slots__.
Someday I'll have time to write up a proper page about why you shouldn't
use __slots__
-- 
Aahz ([EMAIL PROTECTED])   * http://www.pythoncraft.com/

Typing is cheap.  Thinking is expensive.  --Roy Smith
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to protect my new commercial software.

2007-12-18 Thread Grant Edwards
On 2007-12-18, Steven D'Aprano [EMAIL PROTECTED] wrote:
 On Tue, 18 Dec 2007 17:04:29 +, Grant Edwards wrote:

 On 2007-12-18, Jan Claeys [EMAIL PROTECTED] wrote:
 Op Fri, 14 Dec 2007 16:54:35 +, schreef Grant Edwards:

 Uh what?  I don't know what country you're in, but in the US, it
 doesn't take any time at all to copyright something.  The mere act of
 writing something copyrights it.  I thought it was the same in Europe
 as well.

 No, it's only copyrighted when you _publish_ it.
 
 Interesting.  So, in Europe, if somebody steals something you wrote
 before you get it published, they're free to do with it as they please?

 Please do not conflate theft and copyright infringement, or theft and 
 plagiarism.

I wasn't.  If I write something down and somebody steals that
paper, that's theft.

 They are very different concepts, and confusing them does not 
 help.

Sorry if I was unclear.  The stealing was of the medium
containing the authored work.

-- 
Grant Edwards   grante Yow! Used staples are good
  at   with SOY SAUCE!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Strict mode?

2007-12-18 Thread John Machin
On Dec 19, 9:03 am, Jack [EMAIL PROTECTED] wrote:
 While enjoying the dynamic feature of Python I find it difficult to refactor
 code without breaking it. For example, if I modify a function to take more
 arguments, or arguments of different types, I'll need to manually find out
 all places where the function is called and make sure I modify them all,
 unlike in C/Java, where the compiler will do the work of checking function
 signatures, etc.

This specific problem can be addressed at least partially by setting
reasonable defaults for new arguments. This is a necessary technique
when the publisher of a language or a module/package wants to extend
the functionality of a function or method without introducing a new
name for the function/method.

The general problem is usually addressed in dynamic languages by
running a test suite.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Allowing Arbitrary Indentation in Python

2007-12-18 Thread Grant Edwards
On 2007-12-18, Sam [EMAIL PROTECTED] wrote:

 A friend of mine is picking up some Python and is frustrated by
 Python's indentation rules (http://greatbiggary.livejournal.com/
 260460.html?thread=1835884#t1835884).  Personally, I've never had any
 issues with Python's ways of indentation, but that conversation got me
 thinking about the issue.

 Consider the following indentation rules:
 1. Blocks begin with a line ending in :
 2. A line on the same indentation level or lower ends a block.

 Under those rules, this would work:
 layouts = ['column', 'form', 'frame']
 cmds.window(t='gwfUI Builder')
 cmds.paneLayout(configuration='vertical3', ps=((1, 25, 100), (3, 20,
 100)))
 cmds.paneLayout(configuration='horizontal2')
 cmds.frameLayout(l='Layouts')
 cmds.scrollLayout(cr=True)
 cmds.columnLayout(adj=True, cat=('both', 2))
 for i in layouts:
   cmds.button(l=i)
 cmds.setParent('..')
 cmds.setParent('..')
 cmds.setParent('..')
 cmds.setParent('..')
 cmds.setParent('..')
 cmds.showWindow()

And you think that example is an argument in _favor_ of what
you propose?

 Do such rules make sense?

IMO, no.

 Is there any way to make code work that way in Python?

no.

 Should there be?

God no.

Code should work the way it looks and look the way it works.
Changing the language in order to allow authors to mislead
readers is a bad thing.

 Does that make this sort of code more or less readable?

You must be joking.

-- 
Grant Edwards   grante Yow! I joined scientology
  at   at a garage sale!!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >