Re: UnboundLocalError

2006-11-11 Thread Camellia
Oh how can I thank you enough, you make my day:)
According to what you said I finally figure it out, it is the same as:

code
b = 1
def a():
b = b #no good:)
/code

So in every day programming I should avoid using the same name for
different objects because they will step on each other, right?

On Nov 11, 6:18 pm, Gabriel Genellina [EMAIL PROTECTED] wrote:
 At Saturday 11/11/2006 02:35, Camellia wrote:

 But sorry I'm so dumb I can't say I really understand,
 what do I actually do when I define a function with its name number?Don't 
 apologize, Python is a lot more dumb than you. It obeys very
 simple rules (a good thing, so we can clearly understand them, once
 we know them).
 Recalling your previous example:

def main():
   number = number()Python first scans the source code looking for 
assigned-to names.
 That is, names to the left of equal signs. Those names, plus the
 function formal parameters, make the list of local names. Any other
 names referenced are assumed to be globals, that is, living outside
 your function. (That's not entirely true but enough for now).
 Notice that number is a local name because it's assigned to; it
 doesn't matter whether a global name number exists or not.
 When the code is executed, the number to the right references the
 local name, which has not been assigned to yet - that's why you get
 an UnboundLocalError. number can't be a global name when used on
 the right hand side, and a local name when used on the left hand
 side. It's simple: it is local, or not, but not both.

 why does a name of a function has something to do with a variable?Notice 
 also that it does not matter *what* kind of object a name
 refers to: it may be a function, a class, an object instance,
 whatever. Inside a function, by example, a local name a may be
 bound at most to a single object at a time, it doesn't matter its
 type. A local name a can't refer to an integer and a class at the same time.
 The left hand side of an assign statement *always* uses local names,
 except when you declare a name to be global by using the global keyword.
 And notice also that I've never used the word variable.

 Oh wait can I do this in Python?:
 code
 def a():
  def b()
 /code

 so the b() will appear to be a local function which is the possible
 cause of my little own error because the compiler will interpret the
 number() as a local function but a global one?Yes, you can. Python has 
 lexically nested scopes. The simple
 local/global rule of above is a bit more complicated: when a name is
 not local, it is searched inside the enclosing functions, then in the
 containing module's global namespace, and last in the builtin names.
 And yes, b is local to a, so it effectively hides any external b that
 could be in outer scopes.

 --
 Gabriel Genellina
 Softlab SRL

 __
 Correo Yahoo!
 Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
 ¡Abrí tu cuenta ya! -http://correo.yahoo.com.ar

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


Re: UnboundLocalError

2006-11-11 Thread Camellia
Oh how can I thank you enough, you make my day:)
According to what you said I finally figure it out, it is the same as:

code
b = 1
def a():
b = b #no good:)
/code

So in every day programming I should avoid using the same name for
different types of objects because they will step on each other, right?

On Nov 11, 6:18 pm, Gabriel Genellina [EMAIL PROTECTED] wrote:

On Nov 11, 6:18 pm, Gabriel Genellina [EMAIL PROTECTED] wrote:
 At Saturday 11/11/2006 02:35, Camellia wrote:

 But sorry I'm so dumb I can't say I really understand,
 what do I actually do when I define a function with its name number?Don't 
 apologize, Python is a lot more dumb than you. It obeys very
 simple rules (a good thing, so we can clearly understand them, once
 we know them).
 Recalling your previous example:

def main():
   number = number()Python first scans the source code looking for 
assigned-to names.
 That is, names to the left of equal signs. Those names, plus the
 function formal parameters, make the list of local names. Any other
 names referenced are assumed to be globals, that is, living outside
 your function. (That's not entirely true but enough for now).
 Notice that number is a local name because it's assigned to; it
 doesn't matter whether a global name number exists or not.
 When the code is executed, the number to the right references the
 local name, which has not been assigned to yet - that's why you get
 an UnboundLocalError. number can't be a global name when used on
 the right hand side, and a local name when used on the left hand
 side. It's simple: it is local, or not, but not both.

 why does a name of a function has something to do with a variable?Notice 
 also that it does not matter *what* kind of object a name
 refers to: it may be a function, a class, an object instance,
 whatever. Inside a function, by example, a local name a may be
 bound at most to a single object at a time, it doesn't matter its
 type. A local name a can't refer to an integer and a class at the same time.
 The left hand side of an assign statement *always* uses local names,
 except when you declare a name to be global by using the global keyword.
 And notice also that I've never used the word variable.

 Oh wait can I do this in Python?:
 code
 def a():
  def b()
 /code

 so the b() will appear to be a local function which is the possible
 cause of my little own error because the compiler will interpret the
 number() as a local function but a global one?Yes, you can. Python has 
 lexically nested scopes. The simple
 local/global rule of above is a bit more complicated: when a name is
 not local, it is searched inside the enclosing functions, then in the
 containing module's global namespace, and last in the builtin names.
 And yes, b is local to a, so it effectively hides any external b that
 could be in outer scopes.

 --
 Gabriel Genellina
 Softlab SRL

 __
 Correo Yahoo!
 Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
 ¡Abrí tu cuenta ya! -http://correo.yahoo.com.ar

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


Re: Tkinter: How do I change the actual width of a widget?

2006-11-11 Thread Fredrik Lundh
Mudcat wrote:

 I am trying to change the width of a widget based on pixel size and not
 on characters. I can't figure out how to do this.
 
 Normally to change to the size of a widget it looks like:
 
 widget.configure(width = x)
 
 However that is in characters, not in pixels. To retrieve the actual
 size of a widget, I believe it is done with:
 
 x = widget.winfo_width()
 
 Obviously that value can not be used in the configure statement. Is
 there a way to dynamically change the width (and height) of a widget
 using the winfo data?

look for pack_propagate on this page for one way to do it:

 http://effbot.org/tkinterbook/button.htm

/F

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


Re: UnboundLocalError

2006-11-11 Thread Fredrik Lundh
Camellia wrote:

 Oh how can I thank you enough, you make my day:)
 According to what you said I finally figure it out, it is the same as:
 
 code
 b = 1
 def a():
 b = b #no good:)
 /code

if you really want to modify a variable that lives outside the function, 
you can use the global directive:

http://effbot.org/pyfaq/how-do-you-set-a-global-variable-in-a-function.htm

  So in every day programming I should avoid using the same name for
  different types of objects because they will step on each other,
  right?

if you want to distinguish between things, giving them distinct names is 
always a good idea.

/F

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


Re: Inheritance Question

2006-11-11 Thread Frank Millman

Gabriel Genellina wrote:
 At Saturday 11/11/2006 03:31, Frank Millman wrote:

 Continuing your analogy of animals, assume a class A with a 'walk'
 method and an 'eat' method.
 
 Most animals walk the same way, but a few don't, so I create a subclass
 AW and override the walk method.
 
 Most animals eat the same way, but a few don't, so I create a subclass
 AE and override the eat method.
 
 How do I create an instance of an animal that both walks and eats
 differently?
 

[snip]

 Answer 1) Move *both* ways of walk, and *both* ways of eating, to
 another base class. Best when this is pure behavior - no new
 attributes are involved.


[snip details]


 Answer 2) Use an instance of another class to define how to walk and
 how to eat. Advantage: it can later be modified at runtime (strategy pattern).


[snip details]

Many thanks for this, Gabriel.

I have seen explanations like this before, but my eyes usually glaze
over before I have finished, and I end up more confused than when I
started.

With a combination of my subconscious slowly getting an understanding
of this, and your clear explanation, I think I have finally got it.

Obviously my real world situation is quite a bit more complex than this
simple example, but with the help you have given me I can now
experiment with different ideas and decide on the best strategy.

Thanks again

Frank

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


Re: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ?

2006-11-11 Thread Robin Becker
Andrew MacIntyre wrote:

 I guess the freebsd limits  must be different to the original 
 development environment.
 
 The number of semaphores is certainly tunable - the SYSV IPC KERNEL 
 PARAMETERS section in the file /usr/src/sys/conf/NOTES lists the SYSV
 semaphore parameters that can be set in the kernel config.
 

yes those limits look pretty low. I think POSH grabs 60 the first time 
and then fails the second as the limit appears to be 61. I wonder what 
the actual cost is of having lots of semaphores.
-- 
Robin Becker
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how is python not the same as java?

2006-11-11 Thread Jacques Naude
[EMAIL PROTECTED] wrote:
 You can get educated in java through manpower for free just apply for a
 job(through thier online learning thing) but you can't add python to
 your plan.  :(  They have pearl, c, basic, cobol also but no
 python.
 
 https://sourceforge.net/project/showfiles.php?group_id=156455
 
 
 gavino wrote:
 both are interpreted oo langauges..
 
Pearl?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQLdb windows binaries for Python 2.5??

2006-11-11 Thread Henk . van . Asselt
I'm also looking for a MySQLdb binary for windows. This is holding me
from upgrading from Python 2.4 to Python 2.5 !

Or does anybody know of alternatives ?   I have to connect directly to
an MySQL database.

Henk

 HI All,
 Does such a beast exist?  Have been looking but haven't seen any.  Any
 insight would be appreciated.
 
 Thanks.
 
 Chris

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


Re: MySQLdb windows binaries for Python 2.5??

2006-11-11 Thread Robin Becker
[EMAIL PROTECTED] wrote:
 I'm also looking for a MySQLdb binary for windows. This is holding me
 from upgrading from Python 2.4 to Python 2.5 !
 
 Or does anybody know of alternatives ?   I have to connect directly to
 an MySQL database.
 
 Henk
 
 HI All,
 Does such a beast exist?  Have been looking but haven't seen any.  Any
 insight would be appreciated.

 Thanks.

 Chris
 

I'm just trying to build from source and am having problems getting the 
right parameters for the setup.py. It seems mysql-5.0.27 for win32 
doesn't have mysql-config.exe so the setup fails rather miserably.

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


Re: UnboundLocalError

2006-11-11 Thread Camellia
Oh thank you for pointing that out Fredrik, you made the case more
clear:)

On Nov 11, 7:19 pm, Fredrik Lundh [EMAIL PROTECTED] wrote:
 Camellia wrote:
  Oh how can I thank you enough, you make my day:)
  According to what you said I finally figure it out, it is the same as:

  code
  b = 1
  def a():
  b = b #no good:)
  /codeif you really want to modify a variable that lives outside the 
  function,
 you can use the global directive:

 http://effbot.org/pyfaq/how-do-you-set-a-global-variable-in-a-functio...

   So in every day programming I should avoid using the same name for
   different types of objects because they will step on each other,
   right?

 if you want to distinguish between things, giving them distinct names is
 always a good idea.
 
 /F

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


Re: Py3K idea: why not drop the colon?

2006-11-11 Thread Antoon Pardon
On 2006-11-11, Steven D'Aprano [EMAIL PROTECTED] wrote:
 On Fri, 10 Nov 2006 13:16:32 -0600, Michael Hobbs wrote:

 Yeah, okay, I didn't read through the details of the PEP. I picked a bad 
 example to illustrate a point that is still true. The FAQ also tries to 
 argue that it's a Good Thing that join() is a string method, not a list 
 method. It also tries to argue that there's a good reason that lists are 
 different than tuples. I don't think it would surprising that many 
 Python developers don't really buy those arguments either.

 Well, as far as I'm concerned, you've just blown your credibility
 completely out the water now. 

 Yes, I'm aware that there are many Python programmers who don't get join()
 or lists/tuples, but I'm constantly surprised by that fact. At the risk of
 starting another argument, to my mind that's like discovering that there
 are professional butchers who don't think that using a sharp knife is a
 good idea.

Well I would think that if you would find out that many professional
butchers would think so, you might consider the idea has some merrit.

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


Re: service windows avec py2exe

2006-11-11 Thread DarkPearl
I found the function which starts the error

**
class Win32ProcessUsage:
def __init__(self):
self.lstProcess=[]
self.WMIService =
win32com.client.GetObject(rwinmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2)
self.reset()
def reset(self):
self.lstProcess=[]
lstTmp = self.WMIService.ExecQuery('Select * from
Win32_Process')
for item in lstTmp:

self.lstProcess.append(tuple([item.Name,item.CommandLine,item.Status,item.ProcessId,item.ParentProcessId]))

def get_usage(self):
return self.lstProcess
**

it is a class which allows to obtain the list of the processes who run.

With python interpreter, this class functions very well but , when it
turns in service, it starts the error :

The instance's SvcRun() method failed
Error getting traceback - traceback.print_tb() failed
class 'pywintypes.com_error': (-2147221020, 'Syntaxe incorrecte',
None, None)

Why ???

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


Re: urlretrieve get file name

2006-11-11 Thread Sven
 You can use the geturl() method to obtain the true URL used (that
 would behttp://page.com/filename.zip) and then rename the file.

Thanks mate, this was exactly what I needed. A realy clean and simple
solution to my problem. :-)

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


Re: Inheritance Question

2006-11-11 Thread Carl Banks
Jackson wrote:
 For a more concrete example:

 Suppose all the animals in the world have only 1 or 2 legs.

 class Legs(object)
   def run(): pass
   def walk(number_of_legs):
 # lots of commands
 # that do not depend on the
 # number of legs but definitely
 # have to do with walking

 if number_of_legs == '1':
# blah blah

 if number_of_legs == '2':
# blah blah

 # more commands

 class HasAtLeastOneLeg(Legs):
   def walk():
 # Legs.walk(number_of_legs=1)

 class HasTwoLegs(HasAtLeastOneLeg,Legs):
   def walk()
 # Legs.walk(number_of_legs=2)

Well, I would have done this differently.  If the only difference in
behavior between one- and two-legged creatures is their gait, I
probably wouldn't have bothered breaking Legs into subclasses.  I'd
just pass the number of legs into __init__:

class Legs(object):
def __init__(self,number_of_legs):
self.number_of_legs = number_of_legs
def walk(self):
# non-legs-dependent stuff
if self.number_of_legs == 1:
# one-legged gait
elif self.number_of_legs == 2:
# two-legged gait
else:
raise ValueError(invalid number of legs)
# more non-legs-dependent stuff

Then, when defining some sort of monster class, I'd do something like
this:

class Human(object):
def __init__(self):
self.legs = Legs(2)
# etc.

class Dufflepud(object):
def __init__(self):
self.legs = Legs(1)
# etc.

If there's more to it than just gait (say for example, one-legged
creatures attack differently, jump higher, and can't turn invisible
because they don't have enough limbs to cast Level 4 Invisibility),
then I would factor out differences in behavior into subclasses.

class Legs(object):
def walk(self):
# non-leg-related stuff
self.set_gait()
# more non-leg-related stuff

class OneLeg(Legs):
def set_gait(self):
# set the one-legged gait

class TwoLegs(Legs):
def set_gait(self):
# set the two-legged gait

class Human(object):
def __init__(self):
self.legs = TwoLegs()

class Dufflepud(object):
def __init__(self):
self.legs = OneLeg()


ISTM you have been missing out on the true power of inheritance.
Behavior exclusive to creatures with two legs should be implmented in
the TwoLegs class, but in your example you define a HasTwoLegs class
yet still implement this behavior in the base class Legs.  That's just
poor use of inheritance.  My examples implement behavior exclusive to
two-legged creatures inside the TwoLegs class, where it belongs.

In fact, BEHAVIOR is the key to arranging class hierarchies.  (The
classical advice, the inheritance represents the is a relationship,
can be very misleading and I don't recommend using it.  The focus
should be on behavior.)  Anyways, in your universe, there are three
kinds of behaviors:

A. behaviors exclusive to one-footed creatures
B. behaviors exclusive to two-footed creatures
C. behaviors common to both

Once you consider behaviors in this way, how to arrange the class
hierarchy becomes obvious.  Each kind of behavior shoud be implemented
in its own class: common behaviors go into base classes, exclusive
behaviors into subclasses.  The hierarchy should look like this:

class Legs -- this should implement all common behavior
class OneLeg(Legs) -- should implment all behavior exclusive to
one-legged creatures
class TwoLegs(Legs) -- should implment all behavior exclusive to
two-legged creatures

Note that there's no need for an AtLeastOneLeg class.  There are only
one- and two-legged creatures in this univserse, so behaviors exclusive
to creatures with at least one leg apply are in fact common to all
creatures.  But suppose we add zero-footed creatures to the universe.
Now we identify five kinds of behaviors:

A. behaviors common to all creatures
B. behaviors exclusive to zero-footed creatures
C. behaviors common to one- and two-footed creatures
D. behaviors exclusive to one-footed creatures
E. behaviors exclusive to two-footed creatures

Now we need an AtLeastOneLeg class in our hierarchy:

class Legs
class ZeroLegs(Legs)
class AtLeastOneLeg(Legs)
class OneLeg(AtLeastOneLeg)
class TwoLegs(AtLeastOneLeg)

But, notice that we still have a OneLeg class, because there's still
behavior exclusive to one-legged creatures.  It belongs in OneLeg, not
in AtLeastOneLeg.

Hope this long-winded advice helps.


Carl Banks

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


numpy/scipy: correlation

2006-11-11 Thread robert
Is there a ready made function in numpy/scipy to compute the correlation y=mx+o 
of an X and Y fast: 
m, m-err, o, o-err, r-coef,r-coef-err ?

Or a formula to to compute the 3 error ranges?

-robert

PS:

numpy.corrcoef computes only the bare coeff:
 numpy.corrcoef((0,1,2,3.0),(2,5,6,7.0),)
array([[ 1.,  0.95618289],
   [ 0.95618289,  1.]])

with ints it goes computes wrong:
 numpy.corrcoef((0,1,2,3),(2,5,6,7),)
array([[ 1.,  0.94491118],
   [ 0.94491118,  1.]])

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


Re: how is python not the same as java?

2006-11-11 Thread Ben Finney
Jacques Naude [EMAIL PROTECTED] writes:

 [EMAIL PROTECTED] wrote:
  They have pearl, c, basic, cobol also but no python.

 Pearl?

Practical Extraction And Reporting Language.

URL:http://en.wikipedia.org/wiki/Perl#Name

-- 
 \ Lucifer: Just sign the Contract, sir, and the Piano is yours. |
  `\ Ray: Sheesh! This is long! Mind if I sign it now and read it |
_o__) later?  -- http://www.achewood.com/ |
Ben Finney

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


Re: MySQLdb windows binaries for Python 2.5??

2006-11-11 Thread Jan Dries
[EMAIL PROTECTED] wrote:
 I'm also looking for a MySQLdb binary for windows. This is holding me
 from upgrading from Python 2.4 to Python 2.5 !
 

If you search the Help Forum of the MySQLdb project on SourceForge, you 
will find a couple of people who have successfully built MySQLdb on 
Windows for 2.5, and are willing to share their installers.
That's how I got my binaries.

Regards,
Jan


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


import parser does not import parser.py in same dir on win

2006-11-11 Thread Joel Hedlund
Hi!

I have a possibly dumb question about imports. I've written two python 
modules:

parser.py

class Parser(object):
 my parser


app.py

from parser import Parser
print import successful


Running app.py on linux, gives:

import succesful


However, runnning it on windows gives:

Traceback (most recent call last):
   File test.py, line 1, in ?
 from parser import Parser
ImportError: cannot import name Parser


It turns out that on Windows, the builtin parser module is imported 
instead. Why? Why is there a difference? What other names are taken?

In both cases the script dir is first on sys.path, and I'm using the 
plain old terminal/cmd window.

Thanks for your time.

Cheers!
/Joel Hedlund
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: numpy/scipy: correlation

2006-11-11 Thread Robert Kern
robert wrote:
 Is there a ready made function in numpy/scipy to compute the correlation 
 y=mx+o of an X and Y fast: 
 m, m-err, o, o-err, r-coef,r-coef-err ?

numpy and scipy questions are best asked on their lists, not here. There are a
number of people who know the capabilities of numpy and scipy through and
through, but most of them don't hang out on comp.lang.python.

  http://www.scipy.org/Mailing_Lists

scipy.optimize.leastsq() can be told to return the covariance matrix of the
estimated parameters (m and o in your example; I have no idea what you think
r-coeff is).

-- 
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


plasTeX doesn't load LaTeX packages

2006-11-11 Thread giovanni gherdovich
Hello,

first of all:
Is this the right place to ask plastek-related
questions?

I'm trying to make plastex work on my Ubuntu Dapper
Drake. For LaTeX, I have the all-in-one package
tetex.

Everything is ok with this simple helloword code:

\documentclass{article}
\author{Au. Thor}
\title{Title}
\date{\today}
\begin{document}
\maketitle
Hello World!
\end{document}

but if I try to load any package, like in

\documentclass{article}
\usepackage{babel,a4,amsfonts,amsmath,amsthm,amssymb}
\author{Au. Thor}
\title{Title}
\date{\today}
\begin{document}
\maketitle
Hello World!
\end{document}

I got a lot of errors:

$ plastex helloworld.tex
plasTeX version 0.6
 (
/usr/lib/python2.4/site-packages/plasTeX/Packages/article.pyc
)
 ( /usr/share/texmf-tetex/tex/generic/babel/babel.sty
WARNING: Could not find any file named: b
 )
ERROR: Error while expanding usepackage in
/usr/share/texmf-
   tetex/tex/generic/babel/babel.sty on line 145
(Empty module name)
ERROR: Error while expanding usepackage in
/usr/share/texmf-
   tetex/tex/generic/babel/babel.sty on line 145
(Empty module name)
ERROR: An error occurred while building the document
object in /usr/share
   /texmf-tetex/tex/generic/babel/babel.sty on line
145 (Empty module name)
Traceback (most recent call last):
  File /usr/bin/plastex, line 95, in ?
main(sys.argv)
  File /usr/bin/plastex, line 44, in main
tex.parse()
  File
/usr/lib/python2.4/site-packages/plasTeX/TeX.py,
line 376, in parse
for item in tokens:
  File
/usr/lib/python2.4/site-packages/plasTeX/TeX.py,
line 45, in next
return self._next()
  File
/usr/lib/python2.4/site-packages/plasTeX/TeX.py,
line 287, in __iter__
tokens = obj.invoke(self)
  File
/usr/lib/python2.4/site-packages/plasTeX/Base/LaTeX/Packages.py,
line 65, in invoke
self.load(tex, file, a['options'])
  File
/usr/lib/python2.4/site-packages/plasTeX/Base/LaTeX/Packages.py,
line 23, in load
self.ownerDocument.context.loadPackage(tex,
file+self.extension, options)
  File
/usr/lib/python2.4/site-packages/plasTeX/Context.py,
line 250, in loadPackage
result = tex.loadPackage(file, options)
  File
/usr/lib/python2.4/site-packages/plasTeX/TeX.py,
line 184, in loadPackage
for tok in self:
  File
/usr/lib/python2.4/site-packages/plasTeX/TeX.py,
line 287, in __iter__
tokens = obj.invoke(self)
  File
/usr/lib/python2.4/site-packages/plasTeX/Base/LaTeX/Packages.py,
line 65, in invoke
self.load(tex, file, a['options'])
  File
/usr/lib/python2.4/site-packages/plasTeX/Base/LaTeX/Packages.py,
line 23, in load
self.ownerDocument.context.loadPackage(tex,
file+self.extension, options)
  File
/usr/lib/python2.4/site-packages/plasTeX/Context.py,
line 229, in loadPackage
m = __import__(module, globals(), locals())
ValueError: Empty module name

What is wrong?

Best regards,
Giovanni Gherdovich

__
Do You Yahoo!?
Poco spazio e tanto spam? Yahoo! Mail ti protegge dallo spam e ti da tanto 
spazio gratuito per i tuoi file e i messaggi 
http://mail.yahoo.it 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: numpy/scipy: correlation

2006-11-11 Thread Robert Kern
Robert Kern wrote:
 robert wrote:
 Is there a ready made function in numpy/scipy to compute the correlation 
 y=mx+o of an X and Y fast: 
 m, m-err, o, o-err, r-coef,r-coef-err ?

 scipy.optimize.leastsq() can be told to return the covariance matrix of the
 estimated parameters (m and o in your example; I have no idea what you think
 r-coeff is).

Ah, the correlation coefficient itself. Since correlation coefficients are weird
beasts constrained to [-1, 1], standard gaussian errors like you are expecting
for m-err and o-err don't apply. No, there's currently no function in numpy or
scipy that will do something sophisticated enough to be reliable. Here's an 
option:

  http://www.pubmedcentral.nih.gov/articlerender.fcgi?artid=155684

-- 
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: handling many default values

2006-11-11 Thread Alan Isaac
 At Friday 10/11/2006 14:11, Alan G Isaac wrote:
 class Params:
   def __init__(self,**kwargs):
   #set lots of default values
   ...
   #set the deviations from defaults
   self.__dict__.update(kwargs)
 
 Is this a reasonable approach overall?
 (Including the last line.)


Gabriel Genellina wrote in message
news:[EMAIL PROTECTED]
 I'm not sure what you want to do exactly, but a class attribute acts
 as a default instance attribute.

Yes.  I am sorry my question was not clearer.
There are *many* parameters,
and the list can change,
so I want to avoid listing them all in the Param class's __init__ function,
using the strategy above.

Q1: Is this approach reasonable?
(This is a newbie question about unforseen hazards.)
Q2: Is it horrible design to isolate the parameters in a separate class?
(Comment: currently several classes may rely on (parts of) the same
parameter set.)

Thanks,
Alan Isaac


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


Re: Py3K idea: why not drop the colon?

2006-11-11 Thread Steven D'Aprano
On Sat, 11 Nov 2006 01:13:03 -0600, Ron Adam wrote:

 Steven D'Aprano wrote:
 On Fri, 10 Nov 2006 21:24:50 +0100, Bjoern Schliessmann wrote:
 
 Marc 'BlackJack' Rintsch wrote:

 No it doesn't -- look again at the example given above.  It's
 legal syntax in Python but doesn't have the semantics implied by
 the example.
 Sorry, I don't understand -- what is the difference between the
 example as it is and the implied semantics of it?
 
 Inform 6 x == blue or red or yellow is equivalent to the Python
  
 x == blue or x == red or x == yellow
 
 Maybe it should have been expressed as:
 
  x == (blue or red or yellow)


But that has very different semantics still -- since parentheses have the
highest priority, it means evaluate (blue or red or yellow), then test if
x is equal to the result.

It might be useful on occasion to have a construct for x equals blue or
red or yellow in the sense used by normal English or Inform 6. And,
funnily enough, Python has such a construct. You just have to write in
instead of ==, and use a tuple for the terms:

x in (blue, red, yellow)

Not hard to remember, and unambiguous.


-- 
Steven.

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


Python opening multiple thread of matlab

2006-11-11 Thread tsjuan
Hello Python Users,

I've been trying to run multiple thread of Matlab by calling its com
object
via python. However, I keep getting error message that says Python
can't
find the attribute of certain function that I want to execute in
Matlab.

I know the com function is exist, it works just fine if I don't run
within thread.
Below is my sample code, any helps or comments are appreciated.

Thanks,
Tanto

import threading
from win32com.client import Dispatch


class MyThread ( threading.Thread ):

   def __init__(self,matlab_command):
   self.matlab_command = matlab_command
   self.matlab_object = Dispatch('matlab.application.single')
   threading.Thread.__init__(self)

   def run(self):
   execute = getattr(self.matlab_object,'Execute')
   execute(self.matlab_command)

   def awesome_dud(self):
   execute = getattr(self.matlab_object,'Execute')
   execute(self.matlab_command)


a = MyThread('a=1:1:100')
b = MyThread('b=1:1:200')

# Running matlab function through thread (It's not working)
# =

a.start()
b.start()
a.join()
b.join()

# Running matlab function not through thread (it's working)
# =
a.awesome_dud()
b.awesome_dud()

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


Re: handling many default values

2006-11-11 Thread Steven D'Aprano
On Fri, 10 Nov 2006 17:11:24 +, Alan G Isaac wrote:

 My class MyClass reuses many default parameters
 with a small number of changes in each instance.

Let me see that I understand. Are you doing something like this?

# Class takes a lot of arguments
a = MyClass(0, 1, 2, 3, 4, 5, ..., 99)
# and instances vary only by one or two of those args
b = MyClass(0, 2, 2, 3, 4, 5, ..., 99)
c = MyClass(0, 3, 2, 3, 4, 5, ..., 99)
d = MyClass(0, 4, 2, 3, 4, 5, ..., 99)
e = MyClass(0, 5, 2, 3, 4, 5, ..., 99)
...
z = MyClass(0, 26, 2, 3, 4, 5, ..., 99)

If that's the case, I'd seriously rethink your class design. It is hard to
advise a better design without knowing more about the class, but I'd be
surprised if you can't use subclassing to reduce the number of parameters
needed. E.g.:

class MyClass(object):
def __init__(self, arg0):
self.arg0 = arg0
# now fill in arguments 1 through 99 with sensible values

class MyClass2(MyClass):
def __init__(self, arg1):
Just like MyClass, but arg0 has a fixed value and arg1 varies
super(MyClass, self).__init__(fixed value)
self.arg1 = arg1

and so on for as many subclasses that you need.

In the same way, perhaps you can group those arguments. E.g. instead of
this:


class WordProcessingDoc(object):
def __init__(self, page_width, page_height, left_margin, 
right_margin, top_margin, bottom_margin, font_face, 
font_size, font_style, line_size, justification): # and many more
# and many, many more arguments
pass


Create some classes, and pass instances of them to the main class:

class CharStyle(object):
def __init__(self, font_face, font_size, font_style):
pass
class PageStyle(object):
def __init__(self, width, height, left, right, top, bottom):
pass

class WordProcessingDoc(object):
def __init__(self, pagestyle, charstyle, paragraphstyle):
pass



 For various reasons I decided to put all the
 parameters in a separate Params class, instances
 of which reset the default values based on keyword
 arguments, like this:
 
 class Params:
  def __init__(self,**kwargs):
  #set lots of default values
  ...
  #set the deviations from defaults
  self.__dict__.update(kwargs)
 
 Is this a reasonable approach overall?
 (Including the last line.)

(1) If there really is no alternative to a class with many arguments; 
(2) and instances can vary those arguments unpredictably;

then this approach seems reasonable to me. But I really suggest you
rethink your class design.



-- 
Steven.

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


Re: handling many default values

2006-11-11 Thread pgarrone

Alan Isaac wrote:
  At Friday 10/11/2006 14:11, Alan G Isaac wrote:
  class Params:
def __init__(self,**kwargs):
#set lots of default values
...
#set the deviations from defaults
self.__dict__.update(kwargs)
  
  Is this a reasonable approach overall?
  (Including the last line.)


 Gabriel Genellina wrote in message
 news:[EMAIL PROTECTED]
  I'm not sure what you want to do exactly, but a class attribute acts
  as a default instance attribute.

 Yes.  I am sorry my question was not clearer.
 There are *many* parameters,
 and the list can change,
 so I want to avoid listing them all in the Param class's __init__ function,
 using the strategy above.

 Q1: Is this approach reasonable?
 (This is a newbie question about unforseen hazards.)
 Q2: Is it horrible design to isolate the parameters in a separate class?
 (Comment: currently several classes may rely on (parts of) the same
 parameter set.)

 Thanks,
 Alan Isaac
Hi,
 I kind of had a similar problem when I was developing a 3d OO engine.
I had many
bigger things composed of lots of little things, and a lot of code was
spent
initializing the little things in constructors.

So I just passed a reference of the bigger thing to the little thing in
its constructor, thus saving a lot
of parameter passing and variable setup and copying. In the following
example, big is passed to
little's constructor, instead of all of big's variables.

ie.
class big:
   def __init__(self):
  self.v1 = ...
  self.v2 = ...
  self.objects = []
  def assemble(self):
  self.objects.append(little(self, 1))
  self.objects.append(little(self,2))

class little:
   def __init__(self, big, n):
 self.big = big # Now little has access to v1, v2 by self.big.v1
etc
 self.n = n  # This makes it different
  def a_function(self):
 do_something(self.big.v1, self.big.v2)

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


Re: range syntax

2006-11-11 Thread Colin J. Williams
Fredrik Lundh wrote:
 Colin J. Williams wrote:
 
 One of the little irritants of Python is that the range syntax is rather 
 long-winded:
 [Dbg] range(3, 20, 6)
 [3, 9, 15]
 [Dbg]
 It would be nice if one could have something like 3:20:6.
 
 if you find yourself using range a lot, maybe you should check if you 
 couldn't use custom iterators more often.
 
 or use the R helper:
 
   R[3:20:6]
 [3, 9, 15]
   R[:20]
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
   R[0:20:2]
 [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
   R[1:20:2]
 [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
 
 where R is defined as:
 
   class R:
 ... def __getitem__(self, slice):
 ... return range(*slice.indices(slice.stop))
 ...
   R = R()
 
 /F
 
Thanks, this appears to be a bit neater than the numpy version.  On the 
other hand, the numpy version provides a wider functionality.

R[start, stop, increment] is certainly a little simpler than 
range(start, stop, increment).  However, could we not achieve that with:
  R= range
  R(2, 20, 3)
[2, 5, 8, 11, 14, 17]
 

Your point about iterators is well taken, but it seems that the range is 
used sufficiently frequently that some syntactic form would be helpful.

Colin W.

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


Re: import parser does not import parser.py in same dir on win

2006-11-11 Thread Fredrik Lundh
Joel Hedlund wrote:

 It turns out that on Windows, the builtin parser module is imported 
 instead. Why?

the table of built-in modules are checked before searching the path.

 Why is there a difference? What other names are taken?

depends on how the interpreter is built; there's a sys variable that 
contains a list of all built-ins:

 http://effbot.org/pyref/sys.builtin_module_names

/F

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


Re: import parser does not import parser.py in same dir on win

2006-11-11 Thread Joel Hedlund
 the table of built-in modules are checked before searching the path.

I figured as much. But why is the behavior different on linux/win? Is 
this documented somewhere?

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


Re: newbie: minidom

2006-11-11 Thread Paul Watson
Fredrik Lundh wrote:
 Danny Scalenotti wrote:
 
 I'm not able to get out of this ...

 from  xml.dom.minidom import getDOMImplementation

 impl = getDOMImplementation()  // default UTF-8
 doc = impl.createDocument(None, test,None)
 root = doc.documentElement
 root.setAttribute('myattrib', '5')

 print root.toxml()


 I obtain

 test myattrib=5/

 why not this?

 ?xml version=1.0 encoding=UTF-8?
 test myattrib=5/
 
 
 why?  the documents are equivalent, and any XML application that 
 requires an explicit UTF-8 encoding declaration is broken.
 
 /F

Explicit is better than implicit.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie: minidom

2006-11-11 Thread Fredrik Lundh
Paul Watson wrote:

 why?  the documents are equivalent, and any XML application that 
 requires an explicit UTF-8 encoding declaration is broken.
 
 Explicit is better than implicit.

inventing your own XML standard is no way better than using the existing 
one.

/F

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


Re: How to choose the right GUI toolkit ?

2006-11-11 Thread Florian Diesch
Dan Lenski [EMAIL PROTECTED] wrote:

 So, is there another toolkit I should be looking at?  Having something
 that can run easily on Cygwin and native Windows is a priority so that
 I can quickly move programs to new measurement computers.  I like GTK a
 lot and Tk is growing on me too.. are there any higher-level wrapper
 toolkits for GTK and Tk?

For Gtk there's Kiwi http://www.async.com.br/projects/kiwi/



   Florian
-- 
http://www.florian-diesch.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter: How do I change the actual width of a widget?

2006-11-11 Thread Mudcat
Fredrik Lundh wrote:


 look for pack_propagate on this page for one way to do it:

  http://effbot.org/tkinterbook/button.htm

 /F


Thanks!

I had actually seen this, but on the pythonware site where it looks
like this:

f = Frame(master, height=32, width=32)
f.pack_propagate(0) # don't shrink
b = Button(f, text=Sure!)
b.pack(fill=BOTH, expand=1)

I guess somewhere along the way it became necessary to use the pack
function with propagate.As a result, I was having problems getting it
to work and thought I was doing something else wrong.

And I guess I also missed the fact that Tkinter doc updates are being
done on effbot. I just upgraded my python version after a long time,
and I'm finding out all kinds of interesting things.

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


Re: odd problem with watsup and VB6 application with modal dialog

2006-11-11 Thread Rob Williscroft
Grumman wrote in news:[EMAIL PROTECTED] in comp.lang.python:

[snip]

 Roughly, I have a script that fills in a field, sets a combobox, then 
 clicks a button via clickButton. At this point, the python interpreter
 hangs. The only thing I've been able to identify as different about
 this form is that it is set as dialog-modal.
 
 I've managed to work around this by adding a second python script that
 contains just enough code to click the offending button. I call it via
 os.system('start other.py') and it starts in a different process,
 clicks the button then hangs. 
 
 But the main script continues on to fill in the following form, and 
 click another button. When the VB app returns to its starting form, 
 destroying the other form instances, the hung interpreter ends.
 
 This works, but it is quite the ugly kludge isn't it?
 
 Is this a normal behaviour for watsup with modal windows? Is there a 
 saner way around it?

AFAICT the problem is that the clickButton() function calls
the internal windows API function SendMessage(), which waits
for the buttons event handler to return something.

There is an alternative PostMessage(), which returns as soon as
the message is put in the target windows message queue.

A potential proplen with this is that it will return immediately
so the caller will need to wait (time.sleep) until the button 
handler has recieved the message and done something about it.

Here's a rewrite of the winGuiAuto.clickButton function,
post_clickButton() that uses PostMessage:

def post_clickButton( hwnd ):
  '''All code here adapted from winGuiAuto.py
  see http://www.tizmoi.net/watsup/intro.html
  '''
  
  def _buildWinLong(high, low):
'''Build a windows long parameter from high and low words.

See http://support.microsoft.com/support/kb/articles/q189/1/70.asp
'''
return int( 0x  ( (high  16) | (low  0x) ) )
  
  def _postNotifyMessage(hwnd, notifyMessage):
'''Post a notify message to a control.'''
import win32gui
import win32con
import win32api

win32gui.PostMessage(
win32gui.GetParent(hwnd),
win32con.WM_COMMAND,
_buildWinLong(
notifyMessage, win32api.GetWindowLong(hwnd, win32con.GWL_ID)
),
hwnd
  )
  
  import win32con
  _postNotifyMessage( hwnd, win32con.STN_CLICKED )
 
if __name__=='__main__':

  '''Just here to show how it works, this code won't actually 
  work unless you have a sutible GUI programme running.
  '''

  from watsup.winGuiAuto import \
findControl,setEditText, \
findTopWindow,clickButton
  from time import sleep

  def main():
  
  form=findTopWindow(wantedText='Main_Form')
  button=findControl(form,wantedText='Open')

  print 'clicking button to open dialog...'
  post_clickButton(button)

  sleep( 0.5 )
  
  form=findTopWindow(wantedText='Dialog_Form')
  button=findControl(form,wantedText='Close')
  
  print clicking close button
  post_clickButton(button)
  
  main() 

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Assistance needed with PyCon sponsorship system

2006-11-11 Thread Steve Holden
It's that time of year again and the Python Software Foundation is 
cranking up for the fifth PyCon, again this year in Texas.

I am responsible for bringing in the sponsorship funds that help to keep 
this event so reasonably priced, and last year I built a PostgreSQL 
database to help with the emailing and the invoicing. However it needs 
some work, which I may not have time to complete myself, to make it 
easier to use and to improve reporting. Naturally the software, such as 
it is, is written entirely in Python.

Is there anyone out there who'd be prepared to help me with this project?

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


py2exe console removing

2006-11-11 Thread Croteam
Hello,

Can somebody tell me how to I remove console at script installing?



Thanks.

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


Re: Py3K idea: why not drop the colon?

2006-11-11 Thread Ron Adam
Steven D'Aprano wrote:
 On Sat, 11 Nov 2006 01:13:03 -0600, Ron Adam wrote:
 
 Steven D'Aprano wrote:
 On Fri, 10 Nov 2006 21:24:50 +0100, Bjoern Schliessmann wrote:

 Marc 'BlackJack' Rintsch wrote:

 No it doesn't -- look again at the example given above.  It's
 legal syntax in Python but doesn't have the semantics implied by
 the example.
 Sorry, I don't understand -- what is the difference between the
 example as it is and the implied semantics of it?
 Inform 6 x == blue or red or yellow is equivalent to the Python
  
 x == blue or x == red or x == yellow
 Maybe it should have been expressed as:

  x == (blue or red or yellow)
 
 
 But that has very different semantics still -- since parentheses have the
 highest priority, it means evaluate (blue or red or yellow), then test if
 x is equal to the result.
 
 It might be useful on occasion to have a construct for x equals blue or
 red or yellow in the sense used by normal English or Inform 6. And,
 funnily enough, Python has such a construct. You just have to write in
 instead of ==, and use a tuple for the terms:
 
 x in (blue, red, yellow)
 
 Not hard to remember, and unambiguous.

Yes, that is the correct best way to do it, of course.

Funny thing is I tested a variation of the above version in a console and it 
seemed to work, which surprised me.  Now I can't get it to work, scratching 
head.  I don't know exactly what I typed in last night, so I can't figure out 
what subtle (or overlooked obvious) characteristics my test had which gave me 
the misleading results.

Sigh. I did think it was kind of odd it (apparently) worked, which was why I 
phrased it as a suggestion.

Cheers,
Ron

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


Why does this code crash python?

2006-11-11 Thread Mythmon
I am trying to make a program that will basically simulate a chess
clock in python. To do this I have two threads running, one that
updates the currently running clock, and one that watches for a
keypress. I am using the effbot Console module, and that is where I get
the events for the keypresses. But when I press space it crashes
shortly after. The program stops, the Console closes, and windows says
that the program pythonw.exe has had an unexpected reason to shut down.
I am using python2.5.

If there is a simpler way to do this ( I tried without threads but had
some problems with the Console module giving me input right and still
letting the timer display count down ) I would like to know about it. I
am not a very good programmer, and don't have much experience with
python

note: A chess clock is two timers that count down from a set time, and
when you start one of the timer the other stops.

Code below:

import time
import Console
from threading import Thread

c = Console.getconsole()

turn = 0

class timer (Thread):
def run ( self ):
global turn
oldTime = [time.time(), time.time()]
timeLeft = [260, 260]

go = True
while go:
newTime = time.time()
timeLeft[turn] -= newTime - oldTime[turn]
oldTime[turn] = newTime
minutes = [str(int(timeLeft[0]//60)),
str(int(timeLeft[1]//60))]
seconds = [str(timeLeft[0]%60)[0:5],
str(timeLeft[1]%60)[0:5]]

if float(seconds[0])  10: seconds[0] = '0' +
seconds[0][:-1]
if float(seconds[1])  10: seconds[1] = '0' +
seconds[1][:-1]

c.text(3,3,minutes[0] + ':' + seconds[0])
c.text(12,3,minutes[1] + ':' + seconds[1])

time.sleep(.1)

class eventMonitor (Thread):
def run ( self ):
global turn
go = True
while go:
event = c.peek()
if event != None:
c.get()
if event.type == 'KeyPress':
if event.keycode == 32:
if turn == 1: turn = 0
if turn == 0: turn = 1
c.text(10,20,'1')

timer().start()
eventMonitor().start()

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


Re: handling many default values

2006-11-11 Thread Ben Finney
Alan Isaac [EMAIL PROTECTED] writes:

 There are *many* parameters, and the list can change, so I want to
 avoid listing them all in the Param class's __init__ function, using
 the strategy above.

 Q1: Is this approach reasonable?
 (This is a newbie question about unforseen hazards.)
 Q2: Is it horrible design to isolate the parameters in a separate class?
 (Comment: currently several classes may rely on (parts of) the same
 parameter set.)

It's a bad design smell to have functions that accept large numbers of
parameters, many of them optional. Such an interface is difficult to
document, maintain and test.

You should certainly be examining such code and seeing how much of it
can be implemented instead as functions with small, well-defined
parameter lists. This may mean writing more functions, or more layers
of functions, or more classes, or whatever; but having a result that
uses small, well-defined interfaces is a valuable property.

-- 
 \The number of UNIX installations has grown to 10, with more |
  `\ expected.  -- Unix Programmer's Manual, 2nd Ed., 12-Jun-1972 |
_o__)  |
Ben Finney

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


Re: Why does this code crash python?

2006-11-11 Thread Irmen de Jong
[EMAIL PROTECTED] wrote:
 I am trying to make a program that will basically simulate a chess
 clock in python. To do this I have two threads running, one that
 updates the currently running clock, and one that watches for a
 keypress. I am using the effbot Console module, and that is where I get
 the events for the keypresses. But when I press space it crashes
 shortly after. The program stops, the Console closes, and windows says
 that the program pythonw.exe has had an unexpected reason to shut down.
 I am using python2.5.

Try not (re)using an object created in a certain thread in another thread.
You're creating a console object c and use it in both threads.

Try creating the console object for each thread by itself,
i.e. remove the global c = Console.getconsole() and replace
it by a getconsole() inside each thread class.

I don't have the Console module so I don't know if it fixes things
for you, but give it a try :)

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


Re: handling many default values

2006-11-11 Thread George Sakkis
Ben Finney wrote:

 Alan Isaac [EMAIL PROTECTED] writes:

  There are *many* parameters, and the list can change, so I want to
  avoid listing them all in the Param class's __init__ function, using
  the strategy above.
 
  Q1: Is this approach reasonable?
  (This is a newbie question about unforseen hazards.)
  Q2: Is it horrible design to isolate the parameters in a separate class?
  (Comment: currently several classes may rely on (parts of) the same
  parameter set.)

 It's a bad design smell to have functions that accept large numbers of
 parameters, many of them optional. Such an interface is difficult to
 document, maintain and test.

 You should certainly be examining such code and seeing how much of it
 can be implemented instead as functions with small, well-defined
 parameter lists. This may mean writing more functions, or more layers
 of functions, or more classes, or whatever; but having a result that
 uses small, well-defined interfaces is a valuable property.

So I guess you prefer the (os.system, os.spawn*, os.popen*, popen2.*,
commands.*) kitchen sink than the single versatile subprocess.Popen
class, right ? I respectfully disagree, and I'm all for
one-class-does-it-all, as long as most parameters are optional and the
default values address the most typical/reasonable case.

To answer to OP's question, your approach is totally reasonable and
well-known; the csv.Dialect class for example is exactly this, a
parameter-holding class.

George

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


Re: Py3K idea: why not drop the colon?

2006-11-11 Thread Georg Brandl
Ron Adam wrote:
 Michael Hobbs wrote:
 
 The same problem that is solved by not having to type parens around the 
 'if' conditional, a la C and its derivatives. That is, it's unnecessary 
 typing to no good advantage, IMHO. I was coding in Ruby for several 
 months and got very comfortable with just typing the if conditional and 
 hitting return, without any extra syntax. When I came back to Python, I 
 found that I felt annoyed every time I typed the colon, since it 
 obviously isn't required. The FAQ says that the colon increases 
 readability, but I'm skeptical. The indentation seems to provide more 
 than enough of a visual clue as to where the if conditional ends.
 
 I'm not sure why '\'s are required to do multi-line before the colon.

Special cases aren't special enough to break the rules.

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


Your message to IIU awaits moderator approval

2006-11-11 Thread iiu-bounces
Your mail to 'IIU' with the subject

Returned mail: Data format error

Is being held until the list moderator can review it for approval.

The reason it is being held:

ClamAV identified this message as a virus (Worm.Mydoom.M)

Either the message will get posted to the list, or you will receive
notification of the moderator's decision.  If you would like to cancel
this posting, please visit the following URL:


http://amgod.boxhost.net/cgi-bin/mailman/confirm/iiu/cee7316ed79723da5da0d101a94bae18848168ac

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


Re: Why does this code crash python?

2006-11-11 Thread Mythmon
On Nov 11, 11:28 am, Irmen de Jong [EMAIL PROTECTED] wrote:
 You're creating a console object c and use it in both threads.

 Try creating the console object for each thread by itself,
 i.e. remove the global c = Console.getconsole() and replace
 it by a getconsole() inside each thread class.

 I don't have the Console module so I don't know if it fixes things
 for you, but give it a try :)

Well, I tried that, and it did something. It made it so the space bar
switched the clock once, but not a second time. And it still crashed,
but not always at the same time, sometimes it would do it the second
time I hit the space bar, sometimes before I hit it the first time, but
always when i did something that would generate a Console event (moving
the mouse or something). So, I thought it had something to do with
Console not working well with threads, so I took it completely out of
threads and had just the event checking loop run by itself, and it
still crashed. So apparently I am using the Console events wrong. I am
going to try and find some examples online on how to watch for events
with it, but if worse comes to worse I can try and use keyboard hooks,
I've looked at those before, and they might work better.

--Mythmon

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


Re: How to choose the right GUI toolkit ?

2006-11-11 Thread John Henry
BTW: I did a search and found the testnotebook example from:

http://prdownloads.sourceforge.net/pythoncard/testNotebook.zip?download

and tried it out.  There is one error in the widget.py that I have to
get around.  Changed from:

canvas.setFillColor('gray')

to:

try:
canvas.setFillColor('gray')
except:
pass

and then ran it.   Works!

So, yes, you can do Notebook in Python.  I believe what they are saying
is that Notebook isn't supported fully (yet) in the resourceeditor.


Bill Maxwell wrote:
 On 9 Nov 2006 22:48:10 -0800, John Henry [EMAIL PROTECTED]
 wrote:

 Upon closer look, the walkthrough did say:
 
 ***
 from PythonCard import model
 
 Change that so it says:
 
 from PythonCard import dialog, model
 
 Save the code.
 ***
 
 So, it works.


 Thanks for looking into it.  It sounds like either it has been fixed in
 the newer version -- or I didn't do something correctly.  It's been a
 long time, and I was just going by the notes I made back then.









 
 
 
 John Henry wrote:
  Bill Maxwell wrote:
   On 8 Nov 2006 11:49:07 -0800, John Henry [EMAIL PROTECTED]
   wrote:
  
   
   John Salerno wrote:
Dan Lenski wrote:
   
 So, is there another toolkit I should be looking at?
   
I highly recommend wxPython. It's very mature, full-featured, and
portable, and fairly easy to learn as well. I can't really compare it 
to
other toolkits (not having used any of them, except Tkinter), but it's
definitely one of the most popular and well-supported ones out there.
   
http://www.wxpython.org/
   
   I highly recommend that you try PythonCard (which sits on top of
   wxPython).  You can get productive very very quickly.  Take a look at:
   
   http://pythoncard.sourceforge.net/walkthrough1.html
  
  
   I took a brief look at PythonCard almost a year ago and got discouraged
   by what I found, so I stopped looking at it.  I've inserted my notes
   from back then, below.  Does anybody know if these things have been
   fixed in the latest release?
  
   Bill
  
  
   =
   My notes from Fri Dec-23-2005:
  
   This is a list of gripes I have while trying to learn about PythonCard.
   I'm trying to investigate various GUI builders for Python, and
   PythonCard looks promising, but a lot of things are getting in the way.
  
   I installed yesterday, using this installer:
   PythonCard-0.8.1.FIXED.win32.exe
  
   A)  The very first example in the tutorial is wrong!
  
On this page:  http://pythoncard.sourceforge.net/documentation.html
When you follow this link to try something for the very first time:
  
Getting Started in PythonCard by Dan Shafer:
http://pythoncard.sourceforge.net/walkthrough1.html
  
You quickly see that the minimal.py example doesn't even contain
   this line, even though the tutorial refers to it:
  
 
  I am not sure which one you are referring to but in the
  PythonCard\samples\minimal, you will find a minimal.py that says:
 
  #!/usr/bin/python
 
  
  __version__ = $Revision: 1.8 $
  __date__ = $Date: 2005/12/17 15:20:02 $
  
 
  from PythonCard import model
 
 
  class Minimal(model.Background):
  def on_menuFileAbout_select(self, event):
  pass
 
  if __name__ == '__main__':
  app = model.Application(Minimal)
  app.MainLoop()
 
 
 
def on_menuFileAbout_select(self, event):
  
And, of course, if you replace the word pass with this, as
   instructed:
  
result = dialog.alertDialog(self, 'It works!', 'Showing Off')
  
it won't run, because the existing pass line isn't inside a def
   inside of a class.
  
 
  No, it didn't work because the author forgot to mention that you have
  to do a:
 
  from PythonCard import model, dialog
 
  instead of just:
 
  from PythonCard import model
 
  I just tried it and it works.
 
  
   B)  Is the Notebook widget really supported?
  
In the installed file changelog.txt (gets installed as part of
   PythonCard installation), it says:
  
added Notebook component, PageBackground, and testNotebook
sample
  
But, the testNotebook sample is nowhere to be found.
  
 
  I haven't come across a need to use Notebook and so I can not say for
  sure.  Looking at notebook.py, it appears to be just a simple wrapper
  on top of the wxWindow notebook.  I would encourage you to post a
  message to the mailing list and ask there.
 
 
I looked lots of places, including the main SourceForge web site,
   and on the wiki, here:
  
http://wiki.wxpython.org/index.cgi/PythonCard
  
Both the main website and the wiki seem way out of date, and the
   latest dates I could find on both of them are sometime in 2004.
  
 
  Yes, sometime around 2004, the website updating stopped.   Fortunately,
  development didn't.  There are quite a 

httplib continuation packets

2006-11-11 Thread Haakon Riiser
After a long debugging session while scripting my webmail,
I believe I have traced the problem to the way httplib sends
POST requests.

I have compared tcpdump listings from Python 2.4.3 and 2.5.0's
httplib (via urllib/urllib2), Perl's LWP::UserAgent 2.033 and
Firefox 2.0.  Only Python sends the request in such a way that
the mailserver closes the connection before I get any data from
the POST request (immediate FIN packet after the POST request).

httplib always sends the urlencoded POST data in a separate packet
from the HTTP headers, and this seems to cause problems with
the web interface in Ipswitch-IMail/8.05 (the software running on
Doteasy's webmail).

Firefox 2.0 has most of the headers in a single packet, but unlike
httplib, it always places a couple of headers in the continuation
packet as well (usually the content-length and content-type
headers).

LWP::UserAgent 2.033 doesn't use continuation at all, and sends
everything in a single packet.

Is this a bug in httplib or the web server?  Is there a
workaround, or should I use Perl for this?

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


Re: Py3K idea: why not drop the colon?

2006-11-11 Thread Ron Adam
Georg Brandl wrote:
 Ron Adam wrote:
 Michael Hobbs wrote:

 The same problem that is solved by not having to type parens around the 
 'if' conditional, a la C and its derivatives. That is, it's unnecessary 
 typing to no good advantage, IMHO. I was coding in Ruby for several 
 months and got very comfortable with just typing the if conditional and 
 hitting return, without any extra syntax. When I came back to Python, I 
 found that I felt annoyed every time I typed the colon, since it 
 obviously isn't required. The FAQ says that the colon increases 
 readability, but I'm skeptical. The indentation seems to provide more 
 than enough of a visual clue as to where the if conditional ends.

 I'm not sure why '\'s are required to do multi-line before the colon.
 
 Special cases aren't special enough to break the rules.
 
 Georg

A bit of a circular answer.

 Why the rule? - So not to break the rule?


I would guess this probably is more applicable in this case.

 Explicit is better than implicit.


Ron







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


Close program built with py2exe

2006-11-11 Thread Steve Ingram
Hiya,

I've got a problem with a program I've written and want to distribute. It
uses a wxPython dialog and I've built a distribution version with py2exe.
Problem is when I run the .exe under windows I can only stop the program
completely using the task manager. When I close the dialog and check the
task manager, there is still a running process. I think this is probably
the python interpreter that is still running.

Can't find any help anywhere, does anyone know how to get the dialog to
kill the process properly??

Ta very much,

Steve

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


Re: Py3K idea: why not drop the colon?

2006-11-11 Thread Georg Brandl
Ron Adam wrote:
 Georg Brandl wrote:
 Ron Adam wrote:
 Michael Hobbs wrote:

 The same problem that is solved by not having to type parens around the 
 'if' conditional, a la C and its derivatives. That is, it's unnecessary 
 typing to no good advantage, IMHO. I was coding in Ruby for several 
 months and got very comfortable with just typing the if conditional and 
 hitting return, without any extra syntax. When I came back to Python, I 
 found that I felt annoyed every time I typed the colon, since it 
 obviously isn't required. The FAQ says that the colon increases 
 readability, but I'm skeptical. The indentation seems to provide more 
 than enough of a visual clue as to where the if conditional ends.
 
 I'm not sure why '\'s are required to do multi-line before the colon.
 
 Special cases aren't special enough to break the rules.
 
 Georg
 
 A bit of a circular answer.
 
  Why the rule? - So not to break the rule?

You proposed to allow leaving off line continuation '\' only in the
if, for and while headers. This is a special case in my eyes.

 I would guess this probably is more applicable in this case.
 
  Explicit is better than implicit.

Of course, this always applies :)

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


Re: handling many default values

2006-11-11 Thread Alan Isaac
Steven D'Aprano wrote
 (1) If there really is no alternative to a class with many arguments;
 (2) and instances can vary those arguments unpredictably;
 then this approach seems reasonable to me. But I really suggest you
 rethink your class design.

Thanks to all who replied and to George for his specific example.
Steve's comments seem to summarize the overall sentiment:
there is no *general* objection, but I should make sure my
specific implementation really profits from a parameter holding class
(rather than, e.g., a super class in which appropriate defaults are set).
I believe this is the case, since the many parameters can vary
arbitrarily and do not fall into neat groupings.

Also, as an aside, no one objected to using
self.__dict__.update(kwargs)
in the __init__ function of the parameter holding class.

Thanks,
Alan


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


RE: Python opening multiple thread of matlab

2006-11-11 Thread Stefan Schukat
Hello, 

you just forgot to initialize the COM runtime for the separate thread. 
try following:

def __init__(self,matlab_command):
self.matlab_command = matlab_command
threading.Thread.__init__(self)
 
def run(self):
  import pythoncom
  pythoncom.CoInitialize()
try:
matlab_object = Dispatch('matlab.application.single')
execute = getattr(matlab_object,'Execute')
execute(self.matlab_command)
finally:
matlab_object = None
pythoncom.CoUnitialize()


Stefan
 

 -Original Message-
 From: [EMAIL PROTECTED] 
 [mailto:[EMAIL PROTECTED] On 
 Behalf Of tsjuan
 Sent: Saturday, November 11, 2006 2:56 PM
 To: python-list@python.org
 Subject: Python opening multiple thread of matlab
 
 Hello Python Users,
 
 I've been trying to run multiple thread of Matlab by calling 
 its com object via python. However, I keep getting error 
 message that says Python can't find the attribute of certain 
 function that I want to execute in Matlab.
 
 I know the com function is exist, it works just fine if I 
 don't run within thread.
 Below is my sample code, any helps or comments are appreciated.
 
 Thanks,
 Tanto
 
 import threading
 from win32com.client import Dispatch
 
 
 class MyThread ( threading.Thread ):
 
def __init__(self,matlab_command):
self.matlab_command = matlab_command
self.matlab_object = Dispatch('matlab.application.single')
threading.Thread.__init__(self)
 
def run(self):
execute = getattr(self.matlab_object,'Execute')
execute(self.matlab_command)
 
def awesome_dud(self):
execute = getattr(self.matlab_object,'Execute')
execute(self.matlab_command)
 
 
 a = MyThread('a=1:1:100')
 b = MyThread('b=1:1:200')
 
 # Running matlab function through thread (It's not working) # 
 =
 
 a.start()
 b.start()
 a.join()
 b.join()
 
 # Running matlab function not through thread (it's working) # 
 =
 a.awesome_dud()
 b.awesome_dud()
 
 --
 http://mail.python.org/mailman/listinfo/python-list
 
-- 
http://mail.python.org/mailman/listinfo/python-list


explicit self revisited

2006-11-11 Thread Peter Maas
The Python FAQ 1.4.5 gives 3 reasons for explicit self (condensed version):

1. Instance variables can be easily distinguished from local variables.

2. A method from a particular class can be called as
   baseclass.methodname(self, argument list).

3. No need for declarations to disambiguate assignments to local/instance
   variables.

All these reasons are valid and retained by the following suggestion: let
self be represented by the dot, e.g. replace

class someTest(unittest.TestCase):
def setUp(self):
self.ly = yList()
self.m1 = self.ly[0].message
self.m2 = self.ly[1].message
self.m3 = self.ly[2].message

def testList(self):
self.assertEqual(len(self.ly),3)
self.assertEqual(self.m1),Ho)
self.assertEqual(self.m2),HoHo)
self.assertEqual(self.m3),HoHoHo)

by

class x(unittest.TestCase):
def .setUp():
.ly = yList()
.m1 = .ly[0].message
.m2 = .ly[1].message
.m3 = .ly[2].message

def .testList():
.assertEqual(len(.ly),3)
.assertEqual(.m1),Ho)
.assertEqual(.m2),HoHo)
.assertEqual(.m3),HoHoHo)

Methods could still be referenced e.g. as x.testList(someInstance).
The current self syntax could still be valid (for backward compatibility.)
Advantages of the new syntax:

1. Enhanced readability, less verbosity

2. Unambiguous: no need to tell newbies that a virtuous pythoneer
   has to stick to self instead of abbreviate it as s.

3. One argument less for Python OO bolted on propaganda.

The second reason is the most important for me. I consider syntax control
by a code of conduct as lame.

The leading dot syntax could have further advantages:

class x(object):
a =   # static variable
.b = 0  # instance variable

This could replace parameterless __init__ methods. Methods without leading
dots could be considered static without a staticmethod decorator. For
backward compatibility this behaviour should be explicitly activated e.g. by
__autostatic__ = true.

What do you think?

-- 
Regards/Gruesse,

Peter Maas, Aachen
E-mail 'cGV0ZXIubWFhc0B1dGlsb2cuZGU=\n'.decode('base64')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Py3K idea: why not drop the colon?

2006-11-11 Thread Ron Adam
Georg Brandl wrote:
 Ron Adam wrote:
 Georg Brandl wrote:
 Ron Adam wrote:
 Michael Hobbs wrote:

 The same problem that is solved by not having to type parens around the 
 'if' conditional, a la C and its derivatives. That is, it's unnecessary 
 typing to no good advantage, IMHO. I was coding in Ruby for several 
 months and got very comfortable with just typing the if conditional and 
 hitting return, without any extra syntax. When I came back to Python, I 
 found that I felt annoyed every time I typed the colon, since it 
 obviously isn't required. The FAQ says that the colon increases 
 readability, but I'm skeptical. The indentation seems to provide more 
 than enough of a visual clue as to where the if conditional ends.
 I'm not sure why '\'s are required to do multi-line before the colon.
 Special cases aren't special enough to break the rules.

 Georg
 A bit of a circular answer.

  Why the rule? - So not to break the rule?
 
 You proposed to allow leaving off line continuation '\' only in the
 if, for and while headers. This is a special case in my eyes.

I wasn't that specific and it was related to Michael's suggestion the colon 
wasn't needed. If the need for '\' was dropped in multi-line block headers, 
then 
the colon would be required for an obvious reason.

If the requirement for line continuations was omitted for any block header 
starting with a python keyword and ending with a colon, would it still be a 
special case?  It would be a bit less explicit.  Are there situations where you 
would want to explicitly limit a block header to just a single line because of 
some negative consequence?

I'm asking more for just plain curiosity, and not suggesting this actually be 
changed.  In practice I don't think its enough of a issue to warrant changing 
in 
python 2.x.  Although it just may (coin toss here) be beneficial for python 3k 
if extended annotations are implemented.

Ron


 I would guess this probably is more applicable in this case.

  Explicit is better than implicit.
 
 Of course, this always applies :)
 
 Georg

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


reduce to be removed?

2006-11-11 Thread Dustan
According to the following page on Wikipedia:
http://en.wikipedia.org/wiki/Python_%28programming_language%29#Future_development
reduce is going to be removed in python 3.0. It talks of an
accumulation loop; I have no idea what that's supposed to mean. So,

===
 x =\
[[1,2,3],
 [4,5,6],
 [7,8,9]]
 reduce(lambda a,b:a+b,  x,  [])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
===

What's an accumulation loop, and how would I convert this code so it's
compatible with the future 3.0 (preferably in a short sweet expression
that I can embed in a list comprehension)?

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


Re: explicit self revisited

2006-11-11 Thread Fredrik Lundh
Peter Maas wrote:

 What do you think?

cannot all you clueless trolls who cannot think of a single useful thing 
to contribute to Python start your own newsgroup?

/F

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


Re: explicit self revisited

2006-11-11 Thread Fredrik Lundh

 cannot all you clueless trolls who cannot think of a single useful thing 
 to contribute to Python start your own newsgroup?

and before anyone complains; please note that they're working through

 http://www.effbot.org/pyfaq/design-index.htm

one article at a time.  who's going to be the first one to argue that 
Python needs a goto statement ?

/F

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


Re: reduce to be removed?

2006-11-11 Thread Fredrik Lundh
Dustan wrote:

 What's an accumulation loop, and how would I convert this code so it's
 compatible with the future 3.0

the release of Python 3.0 is far away, and nobody knows how it's going 
to look.  trying to be future-compatible at this time is a major waste 
of time and (not quite as wasteful as reopening yet another old let's 
make some pointless change to the language thread, but almost).

surely you must have something better to do with your time ?

/F

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


Re: httplib continuation packets

2006-11-11 Thread Fredrik Lundh
Haakon Riiser wrote:

 Is this a bug in httplib or the web server?

it could be that they're blocking requests from Python's urllib, of 
course.  have you tried overriding the user-agent string ?

/F

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


Re: httplib continuation packets

2006-11-11 Thread Haakon Riiser
[Fredrik Lundh]

 Haakon Riiser wrote:

 Is this a bug in httplib or the web server?

 it could be that they're blocking requests from Python's urllib, of 
 course.  have you tried overriding the user-agent string ?

Yes, and it doesn't help.

By the way, this is the closest thing I've found in the bug tracker:
https://sourceforge.net/tracker/?func=detailatid=105470aid=547093group_id=5470
The bug was closed in 2002 with this comment:

  I changed httplib to send requests as a single packet in rev
   1.60.  The change was made to address a performance problem,
   but happens to fix the problem you had with the bogus
   server, too.

Has someone changed it back since then?

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


Re: How to choose the right GUI toolkit ?

2006-11-11 Thread Jussi Salmela
John Henry wrote:
 BTW: I did a search and found the testnotebook example from:
 
 http://prdownloads.sourceforge.net/pythoncard/testNotebook.zip?download
 
 and tried it out.  There is one error in the widget.py that I have to
 get around.  Changed from:
 
 canvas.setFillColor('gray')
 
 to:
 
 try:
 canvas.setFillColor('gray')
 except:
 pass
 
 and then ran it.   Works!
 
 So, yes, you can do Notebook in Python.  I believe what they are saying
 is that Notebook isn't supported fully (yet) in the resourceeditor.

It's true that the notebook and grid components of wxPython are not 
completely integrated into PythonCard but they can still be used quite 
easily once you figure out how.

The process of figuring out can be made easier by a working example. The 
real life application Blood Pressure Monitor

http://personal.inet.fi/cool/operator/BPMDownload.html

can be used as an example of using the notebook, grid and htmlwin 
widgets in PythonCard.

I use this application to input the pressure values I've registered with 
my own meter and to produce a PDF page with PyChart to hand to my doctor 
to inspect when I visit him twice a year.

Cheers,
Jussi

--
Jussi Salmela
http://personal.inet.fi/cool/operator/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reduce to be removed?

2006-11-11 Thread Dustan
Fredrik Lundh wrote:
 Dustan wrote:

  What's an accumulation loop, and how would I convert this code so it's
  compatible with the future 3.0

 the release of Python 3.0 is far away, and nobody knows how it's going
 to look.  trying to be future-compatible at this time is a major waste
 of time and (not quite as wasteful as reopening yet another old let's
 make some pointless change to the language thread, but almost).

 surely you must have something better to do with your time ?

 /F

It's always nice to know there are such good-natured people ready to
help on this group. Anyway, I figured out a way to get the builtin
function 'sum' to work as I need:
sum([[1,2,3],[4,5,6],[7,8,9]],  [])

On an unrelated note, can anyone explain this unpredictable behavior on
IDLE? I swear I never hit ctrl-c...
==
 help(sum)
Help on built-in function sum in module __builtin__:

sum(...)
sum(sequence, start=0) - value

Returns the sum of a sequence of numbers (NOT strings) plus the
value
of parameter 'start'.  When the sequence is empty, returns start.
Traceback (most recent call last):
  File pyshell#0, line 1, in module
help(sum)
  File C:\Python25\lib\site.py, line 346, in __call__
return pydoc.help(*args, **kwds)
  File C:\Python25\lib\pydoc.py, line 1642, in __call__
self.help(request)
  File C:\Python25\lib\pydoc.py, line 1687, in help
self.output.write('\n')
  File C:\Python25\lib\idlelib\PyShell.py, line 1246, in write
self.shell.write(s, self.tags)
  File C:\Python25\lib\idlelib\PyShell.py, line 1235, in write
raise KeyboardInterrupt
KeyboardInterrupt
==

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


Re: reduce to be removed?

2006-11-11 Thread Virgil Dupras

Dustan wrote:
 According to the following page on Wikipedia:
 http://en.wikipedia.org/wiki/Python_%28programming_language%29#Future_development
 reduce is going to be removed in python 3.0. It talks of an
 accumulation loop; I have no idea what that's supposed to mean. So,

 ===
  x =\
 [[1,2,3],
  [4,5,6],
  [7,8,9]]
  reduce(lambda a,b:a+b,  x,  [])
 [1, 2, 3, 4, 5, 6, 7, 8, 9]
 ===

 What's an accumulation loop, and how would I convert this code so it's
 compatible with the future 3.0 (preferably in a short sweet expression
 that I can embed in a list comprehension)?

itertools.chain or sum(x,[])

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


Re: httplib continuation packets

2006-11-11 Thread Fredrik Lundh
Haakon Riiser wrote:

 Yes, and it doesn't help.

then the server is mostly likely broken beyond repair.

 By the way, this is the closest thing I've found in the bug tracker:
 https://sourceforge.net/tracker/?func=detailatid=105470aid=547093group_id=5470
 The bug was closed in 2002 with this comment:
 
   I changed httplib to send requests as a single packet in rev
1.60.  The change was made to address a performance problem,
but happens to fix the problem you had with the bogus
server, too.
 
 Has someone changed it back since then?

nope; that change buffers the *header* part of the request to avoid 
problems with certain TCP/IP mechanisms; see

 http://svn.python.org/view?rev=27644view=rev

for a discussion.  note that there's still no guarantee that the entire 
header is sent in a single TCP packet.

to see if this really is the problem, you could try moving the call to 
self._send_output() from the end of the endheaders() method to the end 
of the _send_request() method (around line 870 in httplib.py, at least 
in 2.5).

/F

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


Re: numpy/scipy: correlation

2006-11-11 Thread Robert Kern
robert wrote:
 Is there a ready made function in numpy/scipy to compute the correlation 
 y=mx+o of an X and Y fast: 
 m, m-err, o, o-err, r-coef,r-coef-err ?

And of course, those three parameters are not particularly meaningful together.
If your model is truly y is a linear response given x with normal noise then
y=m*x+o is correct, and all of the information that you can get from the data
will be found in the estimates of m and o and the covariance matrix of the
estimates.

On the other hand, if your model is that (x, y) is distributed as a bivariate
normal distribution then y=m*x+o is not a particularly good representation of
the model. You should instead estimate the mean vector and covariance matrix of
(x, y). Your correlation coefficient will be the off-diagonal term after
dividing out the marginal standard deviations.

The difference between the two models is that the first places no restrictions
on the distribution of x. The second does; both the x and y marginal
distributions need to be normal. Under the first model, the correlation
coefficient has no meaning.

-- 
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


Python Parallel Paradigm

2006-11-11 Thread Sandy
In article [EMAIL PROTECTED],
[EMAIL PROTECTED] wrote

Well, I tried that, and it did something. It made it so the space bar
switched the clock once, but not a second time. And it still crashed,
but not always at the same time, sometimes it would do it the second
time I hit the space bar, sometimes before I hit it the first time, but
always when i did something that would generate a Console event (moving
the mouse or something). So, I thought it had something to do with
Console not working well with threads, so I took it completely out of
threads and had just the event checking loop run by itself, and it
still crashed. So apparently I am using the Console events wrong. I am
going to try and find some examples online on how to watch for events
with it, but if worse comes to worse I can try and use keyboard hooks,
I've looked at those before, and they might work better.

Dear Pythonauts,

I usually lurk on the comp.lang.python newsgroup.  I'm not an expert
in the slightest, but I have had a growing feeling that there's
something definitely lacking in the concurrency aspects of Python.  It
is the same problem with Java.  Forgive me if I don't know the right
vocabulary, but Python concurrency seems to be exposed at too low a
level.  It's like assembler:  it's all _possible_ to implement, but in
practise it's very complicated and fragile, glitchy, and really
difficult to extend.  Like programming in Dartmouth BASIC with just
conditionals and goto instructions, before structured programming.

A higher-level system of concurrency, not based on monitors and
locks and great programmer discipline, will ultimately require making
Python 3000 a reality.  

In the meantime, is there anywhere, or any thing, that discusses the
various concurrency options related to Python?  There's Stackless Python
(which I can't make head or tail of; I have been unable to find any
lucid overview, or genuine explanation of the purpose of the design.)  I
know that there's a package for an Erlang system for Python, somewhere
(Parnassus probably).  There's probably a Py-CSP somewhere too.  Lots
of trees, but where's the Wood?

Where are concurrency/distributed models compared and discussed?

With kind regards,

Sandy
-- 
Alexander Anderson [EMAIL PROTECTED]
(Yorkshire, England)

   Where there is no vision, the people perish.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Py3K idea: why not drop the colon?

2006-11-11 Thread skip

 I'm not sure why '\'s are required to do multi-line before the colon.
 Special cases aren't special enough to break the rules.
 
 Georg
 A bit of a circular answer.
 
 Why the rule? - So not to break the rule?
 
 You proposed to allow leaving off line continuation '\' only in the
 if, for and while headers. This is a special case in my eyes.

Ron I wasn't that specific and it was related to Michael's suggestion
Ron the colon wasn't needed. If the need for '\' was dropped in
Ron multi-line block headers, then the colon would be required for an
Ron obvious reason.

But \ is used to continue all sorts of statements/expressions, e.g.:

x = a + \
  b

not just conditionals.

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


Re: reduce to be removed?

2006-11-11 Thread Fredrik Lundh
Dustan wrote:

 It's always nice to know there are such good-natured people ready to
 help on this group.

any special reason why you keep pretending that some random wikipedia 
editor knows more about a future Python release than the people that 
develops Python ?

 Anyway, I figured out a way to get the builtin
 function 'sum' to work as I need:
 sum([[1,2,3],[4,5,6],[7,8,9]],  [])

sum() is designed for adding numbers, not sequences.  abusing it
for sequences leads to inefficient code, and extremely bad worst-
case behaviour, since you end up copying the same data over and
over and over again -- the function even checks for strings for
this very reason:

  sum([123, 456, 789], )
Traceback (most recent call last):
   File stdin, line 1, in ?
TypeError: sum() can't sum strings [use ''.join(seq) instead]

(maybe it should check for other well-known containers as well?)

if you care about writing robust code, why not just use a for-loop,
and the list extend method?

/F

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


Re: Python Parallel Paradigm

2006-11-11 Thread Fredrik Lundh
Sandy wrote:

 I usually lurk on the comp.lang.python newsgroup.  I'm not an expert
 in the slightest, but I have had a growing feeling that there's
 something definitely lacking in the concurrency aspects of Python.

the culprit in this case appears to be Microsoft's console library, 
though.  I'm pretty sure that's not written in Python.

/F

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


Re: explicit self revisited

2006-11-11 Thread Doug

Fredrik Lundh wrote:
 Fredrik Lundh wrote:
  cannot all you clueless trolls who cannot think of a single useful thing
  to contribute to Python start your own newsgroup?

 and before anyone complains; please note that they're working through

  http://www.effbot.org/pyfaq/design-index.htm

That site is a bunch of FUD -
The explicit self is there simply because OOP was tacked onto python as
an afterthought.
Why not just be honest about it.  It's too late to change Python's
syntax.  It just means a little extra typing.  If it really bothers
someone, use s instead of self or else use Ruby.

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


Re: httplib continuation packets

2006-11-11 Thread Haakon Riiser
[Fredrik Lundh]

 Haakon Riiser wrote:

 Yes, and it doesn't help.

 then the server is mostly likely broken beyond repair.

It's not in my power to upgrade the server, unfortunately.
Guess I'll have to use Perl.

 to see if this really is the problem, you could try moving the call to 
 self._send_output() from the end of the endheaders() method to the end 
 of the _send_request() method (around line 870 in httplib.py, at least 
 in 2.5).

Tried this, but the tcpdump still looks the same (two packets: one
with the headers, one with the body), and now it fails with

urllib2.HTTPError: HTTP Error 501: Not Implemented

Nevertheless, I'm fairly sure that the packet fragmentation is
the culprit.  It works perfectly with Perl, even when I make
no effort at all to spoof the browser (no user-agent, referer,
cookies, etc.).

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


Re: reduce to be removed?

2006-11-11 Thread Dustan

Fredrik Lundh wrote:
 Dustan wrote:

  It's always nice to know there are such good-natured people ready to
  help on this group.

 any special reason why you keep pretending that some random wikipedia
 editor knows more about a future Python release than the people that
 develops Python ?

Be careful how you word that - this is the first time I've ever
referenced wikipedia in a question on this forum.

  Anyway, I figured out a way to get the builtin
  function 'sum' to work as I need:
  sum([[1,2,3],[4,5,6],[7,8,9]],  [])

 sum() is designed for adding numbers, not sequences.  abusing it
 for sequences leads to inefficient code, and extremely bad worst-
 case behaviour, since you end up copying the same data over and
 over and over again

Thanks for some quality feedback for a change. Why can't you do that
more often?

 -- the function even checks for strings for
 this very reason:

   sum([123, 456, 789], )
 Traceback (most recent call last):
File stdin, line 1, in ?
 TypeError: sum() can't sum strings [use ''.join(seq) instead]

 (maybe it should check for other well-known containers as well?)

 if you care about writing robust code, why not just use a for-loop,
 and the list extend method?

Because I'm embedding this expression in a list comprehension (as I
stated in my original post), and last time I checked, it's not possible
to treat a for-loop as an expression (which is what a list
comprehension requires).

 /F

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


Re: reduce to be removed?

2006-11-11 Thread Fredrik Lundh
Dustan wrote:

  Because I'm embedding this expression in a list comprehension

because?

/F

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


Re: explicit self revisited

2006-11-11 Thread Fredrik Lundh
Doug (Holton?) wrote:

 and before anyone complains; please note that they're working through

  http://www.effbot.org/pyfaq/design-index.htm
 
 That site is a bunch of FUD -

the official FAQ is a bunch of FUD?  are you sure you know what FUD means?

/F

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


Re: explicit self revisited

2006-11-11 Thread skip

Doug The explicit self is there simply because OOP was tacked onto
Doug python as an afterthought.

Got a reference to support that claim?

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


Re: reduce to be removed?

2006-11-11 Thread Dustan

Fredrik Lundh wrote:
 Dustan wrote:

   Because I'm embedding this expression in a list comprehension

 because?

 /F

Because I thought I would be able to get an answer without revealing
the exact details of what I am doing. I didn't realize that wasn't an
option. I'll try once more to give you an idea of what I'm trying to
accomplish without letting on the details.

 foo =\
[[[1,2,3],[4,5,6],[7,8,9]],
 [[3,2,1],[6,5,4],[9,8,7]]]

Here, foo appears to be a 3-dimensional list - except it's supposed to
be 2-dimensional. The inner-list-of-lists is a result of how I'm
producing the data, and now I want to do a mass-concatenation (or
extending) of the inner-list-of-lists, and come up with this:

 foo == [[1,2,3,4,5,6,7,8,9],[3,2,1,6,5,4,9,8,7]]
True

What's the best way to accomplish this?

It's not quite this simple, but let's just see what you can come up
with the information at hand, and I'll see if I can adapt it to my
needs.

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


Re: py2exe console removing

2006-11-11 Thread Fredrik Lundh
Croteam wrote:

 Can somebody tell me how to I remove console at script installing?

what does installing mean in this context?  if the problem is that you 
get a console window when you run the program without a console (e.g. if 
you start it from the explorer), use windows= instead of console= in 
your setup.py script.

/F

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


Re: reduce to be removed?

2006-11-11 Thread Fredrik Lundh
Dustan wrote:

   Because I'm embedding this expression in a list comprehension

 because?
 
 Because I thought I would be able to get an answer without revealing
 the exact details of what I am doing.

alright, let's try again: why do you need a self-contained reduce 
replacement that can be embedded inside a list comprehension ?

/F

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


Re: explicit self revisited

2006-11-11 Thread Steven D'Aprano
On Sat, 11 Nov 2006 18:09:59 -0600, skip wrote:

 
 Doug The explicit self is there simply because OOP was tacked onto
 Doug python as an afterthought.
 
 Got a reference to support that claim?

Of course not, since it is a classic example of trolling.

By comparison, the way I read the Original Poster, he was sincere if
misguided -- but Doug's bullshit response is a typical attempt to throw
petrol on an already hot situation.


-- 
Steven.

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


Re: Why does this code crash python?

2006-11-11 Thread Mythmon


On Nov 11, 3:23 pm, Dennis Lee Bieber [EMAIL PROTECTED] wrote:
 I have no knowledge of Console, but under Windows I was able to hack
 this (see bottom of post) together using only one non-portable library
 -- msvcrt. Oh, and an ActiveState 2.4 build. I'm not touching 2.5 until
 a lot of 3rd party stuff is rebuilt and installers are available.


And here I am thinking this was going to be an easy project. I haven't
had a chance to work on this since my last message, but that example
should be a good thing, since now i have an example of how threads
/should/ be done. I was pretty much just guessing so far.


  newTime = time.time()
  timeLeft[turn] -= newTime - oldTime[turn]I'd duplicated 
  this form, but it is wrong... when the clock swaps it
 will immediately decrement the current clock by the difference since it
 was last updated!

  if float(seconds[0])  10: seconds[0] = '0' +
  seconds[0][:-1]
  if float(seconds[1])  10: seconds[1] = '0' +
  seconds[1][:-1]I've not handled leading 0s on the seconds field (I 
  tried, but can't
 figure out how to specify zero-filled field width for floats -- works
 for integers)


I ran into the same problem, thats why I did it the way I did, instead
of continuing to wrestle with python's string formatting.

  go = True
  while go:Why define go when it never changes

Whenever I make infinite loops, I put in a control variable so I could
stop it if I want, which I was planning on doing, when the time runs
out or something like that.



 Note that I lock access to timeLeft and side to ensure they don't
 change in the middle of access; may not have been critical, but why risk
 it (and if the code gets expanded so the changes take more time -- or
 multiple look-ups using side).

 getch() doesn't seem to return a value for ctrl-c, so I used
 ctrl-z

 Uh, it also updates the time with an invalid negative before it
 exits G

Now to see if I can get this to work for my self with an example. This
is more a learning project than something that has to be done.

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


Re: explicit self revisited

2006-11-11 Thread Fredrik Lundh
Dennis Lee Bieber wrote:

 one article at a time.  who's going to be the first one to argue that 
 Python needs a goto statement ?

   Especially since there is a comefrom G

ah, good point.  I've updated the FAQ.

/F

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


Decimal() instead of float?

2006-11-11 Thread Michael B. Trausch




Is there a way to use Decimal() by default in Python instead of float? I've no use for the float type, and I have some stuff that would require Decimal(), but it is kind of a pain to try and cast things all over the place all the time. Float is just way too inexact for me.

I am searching around, and I don't see anything helpful, but I could (as always) be missing something... I tried (rather navely) to just do something like:

 import decimal
 float=Decimal
 x=1.1
 x
1.1001
 

But, that didn't work (obviously). It was a shot, anyway. Are there any ideas, or does anyone have a way around this? I would prefer to not have to convert incoming floating point numbers to strings and then convert them to Decimal() types every single time that I want to use them (which would be in *every* case). For example, I have a ZIP code database that can do some processing on its numbers, and the numbers are stored as floating point values (exactly) but Python doesn't get them right; so the Decimal() thing would be needed. *shrugs*

 Thanks a bunch,
 Mike




--



Michael B. Trausch


[EMAIL PROTECTED]




Phone: (404) 592-5746


Jabber IM: [EMAIL PROTECTED]




Demand Freedom! Use open and free protocols, standards, and software!





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

Re: odd problem with watsup and VB6 application with modal dialog

2006-11-11 Thread Grumman
Rob Williscroft wrote:
 Here's a rewrite of the winGuiAuto.clickButton function,
 post_clickButton() that uses PostMessage:

Thanks for the info, I'll give it a try.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Decimal() instead of float?

2006-11-11 Thread Fredrik Lundh
Michael B. Trausch wrote:

 Is there a way to use Decimal() by default in Python instead of float?  

nope.

 For example, I have a ZIP code 
 database that can do some processing on its numbers, and the numbers are 
 stored as floating point values (exactly) but Python doesn't get them 
 right

sounds odd.  are you sure you don't mean stored as strings containing 
decimal numbers ?

(who uses fractional ZIP codes, btw?)

/F

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


Re: Py3K idea: why not drop the colon?

2006-11-11 Thread Dan Lenski
Hendrik van Rooyen wrote:
 Fredrik Lundh [EMAIL PROTECTED] wrote:

 8---
color = blue
if color == red or green or yellow:
  ... print color, is red or green or yellow
  ...
  blue is red or green or yellow

 *grin* - this can be construed as a weakness in Python -

 Even COBOL compilers in the sixties would add in the implied
 if color =  after each 'or', instead of bloody - mindedly thinking:

How the heck could this be considered a weakness in Python?  I *like*
the fact that Python does not do anything automagical and rewrite
expressions, thinking it's smarter than the programmer.  That's one
reason I got sick of Perl.

There are plenty of cases where I might want to use an expression like
color == red or foo or bar with the semantics it actually implies in
Python.  Making an exception for literal strings specifically seems
reallly dubious given the fact that Python already has an easy way to
do what you want with the color in (red, green, blue) construct.
This supposedly lacking feature would only be desired by people who
have been brain-damaged by programming languages like BASIC and
COBOL... or newbies who haven't programmed enough to really get
Boolean logic.  /rant

Dan

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


Re: reduce to be removed?

2006-11-11 Thread Dustan

Fredrik Lundh wrote:
 Dustan wrote:

Because I'm embedding this expression in a list comprehension
 
  because?
  
  Because I thought I would be able to get an answer without revealing
  the exact details of what I am doing.

 alright, let's try again: why do you need a self-contained reduce
 replacement that can be embedded inside a list comprehension ?

 /F


 foo =\
[[[1,2,3],[4,5,6],[7,8,9]],
 [[3,2,1],[6,5,4],[9,8,7]]]

Here, foo appears to be a 3-dimensional list - except it's supposed to
be 2-dimensional. The inner-list-of-lists is a result of how I'm
producing the data, and now I want to do a mass-concatenation (or
extending) of the inner-list-of-lists, and come up with this result:

 foo == [[1,2,3,4,5,6,7,8,9],[3,2,1,6,5,4,9,8,7]]
True

What's the best way to accomplish this?

It's not quite this simple, but let's just see what you can come up
with the information at hand, and I'll see if I can adapt it to my
needs.

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


Re: reduce to be removed?

2006-11-11 Thread Robert Kern
Dustan wrote:
 Fredrik Lundh wrote:

 if you care about writing robust code, why not just use a for-loop,
 and the list extend method?
 
 Because I'm embedding this expression in a list comprehension (as I
 stated in my original post), and last time I checked, it's not possible
 to treat a for-loop as an expression (which is what a list
 comprehension requires).

As with all such things, you stick the implementation in a well-named function
and simply call the function everywhere. The implementation never needs to be a
one-liner expression.

-- 
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: Decimal() instead of float?

2006-11-11 Thread Steven D'Aprano
On Sun, 12 Nov 2006 02:31:04 +0100, Fredrik Lundh wrote:

 For example, I have a ZIP code 
 database that can do some processing on its numbers, and the numbers are 
 stored as floating point values (exactly) but Python doesn't get them 
 right
 
 sounds odd.  are you sure you don't mean stored as strings containing 
 decimal numbers ?
 
 (who uses fractional ZIP codes, btw?)

Well, I can't speak for Americans, but here in Australia we typically give
our post codes to six decimal places:

Melbourne 3000.00
Brunswick 3056.00
Clifton Hill 3068.00
Sydney 2000.00
St Johns Park 2176.00

and so forth. You can't have too much precision with those floating point
post/ZIP codes!


-- 
Steven.

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


Re: reduce to be removed?

2006-11-11 Thread Fredrik Lundh
Dustan wrote:

 foo =\
 [[[1,2,3],[4,5,6],[7,8,9]],
  [[3,2,1],[6,5,4],[9,8,7]]]
 
 Here, foo appears to be a 3-dimensional list - except it's supposed to
 be 2-dimensional. The inner-list-of-lists is a result of how I'm
 producing the data, and now I want to do a mass-concatenation (or
 extending) of the inner-list-of-lists, and come up with this result:
 
 foo == [[1,2,3,4,5,6,7,8,9],[3,2,1,6,5,4,9,8,7]]
 True

that still doesn't explain your the expression must be used in a list 
comprehension requirement, though.  assuming that the sizes are 
varying, and at least sometimes a lot larger than 3x3, I'd probably 
write the above as

 for index, item in enumerate(foo):
 this = []
 for i in item:
 this.extend(i)
 foo[index] = this

which should be pretty efficient, since it avoids unnecessary function 
calls, and is amortized linear time instead of O(N**2).

or, if I was in a hurry, and didn't really care if the inner sequences 
were lists or tuples:

foo = map(Tkinter._flatten, foo)

/F

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


Re: reduce to be removed?

2006-11-11 Thread Steven D'Aprano
On Sat, 11 Nov 2006 17:42:32 -0800, Dustan wrote:

 alright, let's try again: why do you need a self-contained reduce
 replacement that can be embedded inside a list comprehension ?

 /F
 
 
 foo =\
 [[[1,2,3],[4,5,6],[7,8,9]],
  [[3,2,1],[6,5,4],[9,8,7]]]
 
 Here, foo appears to be a 3-dimensional list - except it's supposed to
 be 2-dimensional. The inner-list-of-lists is a result of how I'm
 producing the data, and now I want to do a mass-concatenation (or
 extending) of the inner-list-of-lists, and come up with this result:
 
 foo == [[1,2,3,4,5,6,7,8,9],[3,2,1,6,5,4,9,8,7]]
 True
 
 What's the best way to accomplish this?

I don't know if this is the best, but it didn't take long to come up with
it:

 foo = [[[1,2,3],[4,5,6],[7,8,9]],
... [[3,2,1],[6,5,4],[9,8,7]]]

 def unroll(list3d):
... newl = []
... for sublist in list3d:
... newl.append(sum(sublist, []))
... return newl
...
 bar = unroll(foo)
 bar
[[1, 2, 3, 4, 5, 6, 7, 8, 9], [3, 2, 1, 6, 5, 4, 9, 8, 7]]


Repeat after me: 

Not everything has to be a one-liner.


If sum() is too slow, because your sub-lists are huge, you can easily
factor that out and replace it with something using extend.


-- 
Steven.

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


Re: how is python not the same as java?

2006-11-11 Thread Bryan
Jorge Vargas wrote:


 
 the pyc files are just a catching system for the common python
 developer, as for the java developer the .class files are executable
 code. In python noone runs the pyc files, the interpreter takes care
 of this for you.
 

this is an incorrect statement.  we (the company i work for) only ship the
pyc files, and our customers _only_ run the pyc files.  and our embedded
python contains no .py files.  from our perspective,  java .class files and
python .pyc files are treated exactly the same.  and there is very little
difference between jar files containing .class files and zip files
containing .pyc files.


bryan

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


Re: reduce to be removed?

2006-11-11 Thread Dustan

Robert Kern wrote:
 Dustan wrote:
  Fredrik Lundh wrote:

  if you care about writing robust code, why not just use a for-loop,
  and the list extend method?
 
  Because I'm embedding this expression in a list comprehension (as I
  stated in my original post), and last time I checked, it's not possible
  to treat a for-loop as an expression (which is what a list
  comprehension requires).

 As with all such things, you stick the implementation in a well-named function
 and simply call the function everywhere. The implementation never needs to be 
 a
 one-liner expression.

It's already in a function, but in order to convert the reduce function
into a for-loop that I can use as an expression, I would have to create
another independent function, which would make that code more cluttered
than it already is.

Unless you're saying to perform the list comprehension manually. That
would be two for-loops I use in the list comprehension, plus another
one to take place of the reduce function. Sure, that spreads out each
individual step a little more, but it also makes it more difficult to
understand what the overall goal of the code is (I'm going for
readability as well as easy maintenance here).

 --
 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: reduce to be removed?

2006-11-11 Thread Dustan

Fredrik Lundh wrote:
 Dustan wrote:

  foo =\
  [[[1,2,3],[4,5,6],[7,8,9]],
   [[3,2,1],[6,5,4],[9,8,7]]]
 
  Here, foo appears to be a 3-dimensional list - except it's supposed to
  be 2-dimensional. The inner-list-of-lists is a result of how I'm
  producing the data, and now I want to do a mass-concatenation (or
  extending) of the inner-list-of-lists, and come up with this result:
 
  foo == [[1,2,3,4,5,6,7,8,9],[3,2,1,6,5,4,9,8,7]]
  True

 that still doesn't explain your the expression must be used in a list
 comprehension requirement, though.

Oh, right; sorry about the confusion. The list isn't quite that simple,
and in order to pull the right pieces together, I use a list
comprehension.

 assuming that the sizes are
 varying, and at least sometimes a lot larger than 3x3, I'd probably
 write the above as

  for index, item in enumerate(foo):
  this = []
  for i in item:
  this.extend(i)
  foo[index] = this

I'll see if that works.

 which should be pretty efficient, since it avoids unnecessary function
 calls, and is amortized linear time instead of O(N**2).

 or, if I was in a hurry, and didn't really care if the inner sequences
 were lists or tuples:

   foo = map(Tkinter._flatten, foo)

 /F

Steven D'Aprano wrote:
 I don't know if this is the best, but it didn't take long to come up with
 it:

  foo = [[[1,2,3],[4,5,6],[7,8,9]],
 ... [[3,2,1],[6,5,4],[9,8,7]]]
 
  def unroll(list3d):
 ... newl = []
 ... for sublist in list3d:
 ... newl.append(sum(sublist, []))
 ... return newl

deja vu...

  bar = unroll(foo)
  bar
 [[1, 2, 3, 4, 5, 6, 7, 8, 9], [3, 2, 1, 6, 5, 4, 9, 8, 7]]


 Repeat after me:

 Not everything has to be a one-liner.

Not everything has to be a one-liner. But readability helps.

 If sum() is too slow, because your sub-lists are huge, you can easily
 factor that out and replace it with something using extend.
 
 
 -- 
 Steven.

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


Re: explicit self revisited

2006-11-11 Thread Steven D'Aprano
On Sat, 11 Nov 2006 22:39:37 +0100, Peter Maas wrote:

[snip]
 let self be represented by the dot, e.g. replace
 
 class someTest(unittest.TestCase):
 def setUp(self):
 self.ly = yList()
 self.m1 = self.ly[0].message
 self.m2 = self.ly[1].message
 self.m3 = self.ly[2].message
 
 by
 
 class x(unittest.TestCase):
 def .setUp():
 .ly = yList()
 .m1 = .ly[0].message
 .m2 = .ly[1].message
 .m3 = .ly[2].message

On the assumption that Peter was sincere, and not trolling, I thought I'd
make a point-by-point response, but then X crashed and took my post with
it. So here's the brief version.

Implicit self will never be used for Python, because it is redundant so
long as there is a need for explicit self, and there is a need for
explicit self because there are a number of basic, dare I say
*fundamental* programming techniques that require an explicit self.

For example, delegation.

class MyClass(Parent):
def method(self, arg):
Parent.method(self, arg)
# what are you going to write? Parent.method(,arg) maybe?

Here's another fundamental technique that implicit self breaks.

class MyList(list):
def __iadd__(self, other):
# in-place addition
other = transform(other) # do something to the argument
super(MyList, self).__iadd__(other) # call the superclass
# could be written .__class__.__iadd__(other)
# BUT be aware the semantics are NOT the same!
return self  # and return the suitably modified instance

You can't explicitly return the instance unless you have an explicit name
for it. (And if you are thinking of creating more magic syntax that
implicitly returns self, just don't bother.)

Even more fundamentally, any time you need to pass the instance to a
function, you need an explicit self. (Delegation is a special case of this.)

def __str__(self):
# I like semicolons and dislike square brackets.
return ';'.join(self)



-- 
Steven.

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


Re: reduce to be removed?

2006-11-11 Thread Robert Kern
Dustan wrote:
 Robert Kern wrote:
 Dustan wrote:
 Fredrik Lundh wrote:
 if you care about writing robust code, why not just use a for-loop,
 and the list extend method?
 Because I'm embedding this expression in a list comprehension (as I
 stated in my original post), and last time I checked, it's not possible
 to treat a for-loop as an expression (which is what a list
 comprehension requires).
 As with all such things, you stick the implementation in a well-named 
 function
 and simply call the function everywhere. The implementation never needs to 
 be a
 one-liner expression.
 
 It's already in a function, but in order to convert the reduce function
 into a for-loop that I can use as an expression, I would have to create
 another independent function, which would make that code more cluttered
 than it already is.
 
 Unless you're saying to perform the list comprehension manually. That
 would be two for-loops I use in the list comprehension, plus another
 one to take place of the reduce function. Sure, that spreads out each
 individual step a little more, but it also makes it more difficult to
 understand what the overall goal of the code is (I'm going for
 readability as well as easy maintenance here).

Let's just say that we disagree entirely on what constitutes readability and
maintainability.

-- 
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: odd problem with watsup and VB6 application with modal dialog

2006-11-11 Thread ina
At my work we had the same problem.  We found that the best solution
was to use a thread with the code to handle the model dialog.  This
worked best for us because the only models in our product are the error
messages, and using a thread gave us the ability to check and see if
the modal dialog was found.

In this post there is some example code.  I will post up a more
complete solution when I get to work on monday.

http://groups.google.com/group/comp.lang.python/browse_thread/thread/ea9a63aaeaecb591/ee7ec7cf2d12801d?lnk=gstq=findtopwindowrnum=1hl=en#ee7ec7cf2d12801d

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


Re: Py3K idea: why not drop the colon?

2006-11-11 Thread Ron Adam
[EMAIL PROTECTED] wrote:
  I'm not sure why '\'s are required to do multi-line before the 
 colon.
  Special cases aren't special enough to break the rules.
  
  Georg
  A bit of a circular answer.
  
  Why the rule? - So not to break the rule?
  
  You proposed to allow leaving off line continuation '\' only in the
  if, for and while headers. This is a special case in my eyes.
 
 Ron I wasn't that specific and it was related to Michael's suggestion
 Ron the colon wasn't needed. If the need for '\' was dropped in
 Ron multi-line block headers, then the colon would be required for an
 Ron obvious reason.
 
 But \ is used to continue all sorts of statements/expressions, e.g.:
 
 x = a + \
   b
 
 not just conditionals.
 
 Skip

Of course, and your point is?

How about if it be ok to continue to use '\' in headers, but it also be ok to 
not to?  That would be the backward compatible way to change it.

This doesn't answer the question I was asking, are there any situation where it 
would cause problems?  And if so, that reason would be a good and explicit 
reason for not making such a change.

Ron


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


Lisp additions to Docstring Wikipedia entry?

2006-11-11 Thread paddy3118
Hello,
I have just expanded the Wikipedia stub article on docstrings at
http://en.wikipedia.org/wiki/Docstring.
Unfortunately I do not know about Lisp, but took the time to google and
found a link to the GNU Emacs Lisp entry: documentation at:
http://ftp.gnu.org/gnu/Manuals/elisp-manual-20-2.5/html_chapter/elisp_24.html#SEC361
.

If someone, more knowledgeable about Lisp, and interested in Wikipedia
could flesh out the Lisp part...

Thanks for your time.

- Paddy.

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


Re: reduce to be removed?

2006-11-11 Thread Paddy

Dustan wrote:

 Anyway, I figured out a way to get the builtin
 function 'sum' to work as I need:
 sum([[1,2,3],[4,5,6],[7,8,9]],  [])


Hah!
No-one expects sum to be used on anything but numbers.

Except lists as above.

No-one expects sum to be used on anything but numbers, and maybe lists
too.

;-)


(My apologies for my poor grasp of the Spanish Inquisition sketch; and
I was alluding to
this thread:
http://groups.google.com/group/comp.lang.python/msg/f34525384f8028b5 )

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


[ python-Bugs-1594742 ] Word should be changed on page 3.6.1

2006-11-11 Thread SourceForge.net
Bugs item #1594742, was opened at 2006-11-11 10:35
Message generated for change (Tracker Item Submitted) made by Item Submitter
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1594742group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: Documentation
Group: Python 2.5
Status: Open
Resolution: None
Priority: 5
Private: No
Submitted By: jikanter (jikanter)
Assigned to: Nobody/Anonymous (nobody)
Summary: Word should be changed on page 3.6.1

Initial Comment:

The documentation currently reads as follows:

startswith( prefix[, start[, end]])
Return True if string starts with the prefix,
otherwise return False. prefix can also be a tuple of
suffixes to look for. With optional start, test string
beginning at that position. With optional end, stop
comparing string at that position.

Changed in version 2.5: Accept tuples as prefix. 


I believe that in the line that starts with prefix can
also..., the word suffixes should be changed to the
word prefixes.

Thanks for all the good work.  Let me know if you have
any questions.

--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1594742group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[ python-Bugs-1594758 ] Make docu for dict.update more clear

2006-11-11 Thread SourceForge.net
Bugs item #1594758, was opened at 2006-11-11 18:37
Message generated for change (Tracker Item Submitted) made by Item Submitter
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1594758group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: Documentation
Group: Python 2.5
Status: Open
Resolution: None
Priority: 5
Private: No
Submitted By: Christoph Zwerschke (cito)
Assigned to: Nobody/Anonymous (nobody)
Summary: Make docu for dict.update more clear

Initial Comment:
In Note (9) to the mapping types documentation
(http://docs.python.org/lib/typesmapping.html), it
should be mentioned that dict.update returns None to
remind you that it changes the dict in place.

Also, the description should more precisely say
updates (and overwrites) `a` with key/value pairs from
`b` instead of updates (and overwrites) key/value
pairs from `b`.

--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1594758group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



  1   2   >